推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
reapear
V2EX  ›  Python

求教 Fastapi 如何连续返回数据呀

  •  
  •   reapear · Apr 11, 2024 · 3027 views
    This topic created in 761 days ago, the information mentioned may be changed or developed.

    比如我调用 api 执行一个任务,然后在任务中实时返回消息。类似下面这种逻辑

    @app.get("/")
    async def root():
        for i in range(10):
        	time.sleep(1)
            yield str(i)
    
    9 replies    2024-04-12 14:51:48 +08:00
    stay4u
        1
    stay4u  
       Apr 11, 2024
    噗,还能这么写?
    street000
        2
    street000  
       Apr 11, 2024   ❤️ 3
    SSE 或 WebSocket
    chaunceywe
        3
    chaunceywe  
       Apr 11, 2024
    from fastapi import FastAPI
    from fastapi.responses import StreamingResponse

    app = FastAPI()


    async def fake_video_streamer():
    for i in range(10):
    yield b"some fake video bytes"


    @app.get("/")
    async def main():
    return StreamingResponse(fake_video_streamer())
    datadump
        4
    datadump  
       Apr 11, 2024
    @street000 good idea!
    reapear
        5
    reapear  
    OP
       Apr 11, 2024
    @street000 感谢,了解了一下 WebSocket 这种是我想要的效果。
    reapear
        6
    reapear  
    OP
       Apr 11, 2024
    @chaunceywe 这个好像,会等待所有 yield 结果才一起返回。
    mmdsun
        7
    mmdsun  
       Apr 12, 2024 via iPhone   ❤️ 1
    @app.route("/sse", methods=["GET"])
    def write():
    def generate():
    s = "output it token by token test output it token by token test"
    for c in s:
    yield c
    time.sleep(0.02)

    return Response(stream_with_context(generate()))

    用浏览器试试看,输出效果是逐字的。不是整个返回
    TomCN
        8
    TomCN  
       Apr 12, 2024   ❤️ 1
    @reapear #6 如果你使用 postman 或者 swagger ,是会接收完成后显示的,你可以试着写一个 get 方法,浏览器直接访问接口,然后就会一部分一部分的显示出来了,前端页面接收的话,要使用 fetch 来请求
    realJamespond
        9
    realJamespond  
       Apr 12, 2024
    spring 可以用 defered response 配合长轮询
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5657 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 56ms · UTC 07:31 · PVG 15:31 · LAX 00:31 · JFK 03:31
    ♥ Do have faith in what you're doing.