V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 19 天前 · 1230 次点击

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

    @app.get("/")
    async def root():
        for i in range(10):
        	time.sleep(1)
            yield str(i)
    
    9 条回复    2024-04-12 14:51:48 +08:00
    NickLuan
        1
    NickLuan  
       19 天前
    噗,还能这么写?
    street000
        2
    street000  
       19 天前   ❤️ 3
    SSE 或 WebSocket
    chaunceywe
        3
    chaunceywe  
       19 天前
    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())
    wjx0912
        4
    wjx0912  
       18 天前
    @street000 good idea!
    reapear
        5
    reapear  
    OP
       18 天前
    @street000 感谢,了解了一下 WebSocket 这种是我想要的效果。
    reapear
        6
    reapear  
    OP
       18 天前
    @chaunceywe 这个好像,会等待所有 yield 结果才一起返回。
    mmdsun
        7
    mmdsun  
       18 天前 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  
       18 天前   ❤️ 1
    @reapear #6 如果你使用 postman 或者 swagger ,是会接收完成后显示的,你可以试着写一个 get 方法,浏览器直接访问接口,然后就会一部分一部分的显示出来了,前端页面接收的话,要使用 fetch 来请求
    realJamespond
        9
    realJamespond  
       18 天前
    spring 可以用 defered response 配合长轮询
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2509 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:04 · PVG 20:04 · LAX 05:04 · JFK 08:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.