FastAPI 使用 StreamingResponse() 作为输出。参数传入一个不断 yield 的异步函数。
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio
app = FastAPI()
@app.get("/stream")
async def stream_api():
async def event_generator():
for i in range(5):
yield f"data: message {i}\n\n"
await asyncio.sleep(1)
return StreamingResponse(
event_generator(),
media_type="text/event-stream"
)
需要确保规范的几处是:
- 每一条信息的后面要加两个换行
\n\n - media_type 为 text/event-stream
Nginx 默认开启缓冲,要确保禁用,否则所有消息会等到最后一下子发送。
proxy_buffering off;
proxy_cache off;
proxy_http_version 1.1;