当前位置:   article > 正文

【大模型应用开发-FastAPI框架】(十一) Fastapi使用SSE实现流式输出_fastapi流式输出

fastapi流式输出

一、SSE介绍

服务端推送
服务器推送技术中,服务器在消息可用后立即主动向客户端发送消息。其中,有两种类型的服务器推送:SSE和 WebSocket。

SSE(Server-Send Events)
SSE 是一种在基于浏览器的 Web 应用程序中仅从服务器向客户端发送文本消息的技术。SSE基于 HTTP 协议中的持久连接, 具有由 W3C 标准化的网络协议和 EventSource 客户端接口,作为 HTML5 标准套件的一部分。

二、使用SSE实现流式输出

1、安装依赖库

  1. pip install asyncio
  2. pip install sse-starlette

2、后端代码

  1. import json
  2. from fastapi import FastAPI, Query, Path
  3. import uvicorn
  4. from starlette.requests import Request
  5. import asyncio
  6. from sse_starlette import EventSourceResponse
  7. app = FastAPI()
  8. @app.get("/stream")
  9. async def flush_stream(request: Request):
  10. async def event_generator(request: Request):
  11. res_str = "这是一个流式输出他会将每个字挨个挨个的输出哈哈!!!"
  12. for idx, word in enumerate(res_str):
  13. if await request.is_disconnected():
  14. print("连接已中断")
  15. break
  16. data = json.dumps({"id": idx, "message": word}, ensure_ascii=False)
  17. yield data
  18. await asyncio.sleep(1)
  19. return EventSourceResponse(event_generator(request))
  20. if __name__ == '__main__':
  21. uvicorn.run("Run:app", host="0.0.0.0", port=8080)

三、测试

四、客户端监听 SSE 事件

客户端需要监听服务器发送的事件。在浏览器中,可以使用 JavaScript 的 EventSource 对象来监听 SSE。

  1. const eventSource = new EventSource('/stream');
  2. eventSource.onmessage = function(event) {
  3. console.log(event.data);
  4. };
  5. eventSource.onerror = function(error) {
  6. console.error('EventSource failed:', error);
  7. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/880323
推荐阅读
相关标签
  

闽ICP备14008679号