from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio
import uvicorn
import json
#异步队列
msg_queue: asyncio.Queue = asyncio.Queue()
app = FastAPI()
async def my_test_project():
res_list = ["我", "是", "一个", "测试", "程序"]
for msg in res_list:
await msg_queue.put({"type": "msg", "msg": msg})
await asyncio.sleep(0.5)
await msg_queue.put({"type": "done", "msg": ""})
async def generate_data():
# 异步执行任务 在后台齐了一个任务,负责生产数据. --生成者
asyncio.create_task(my_test_project())
#消费数据 ---消费者
#生产者和消费者之间,通过一个队列进行通信,进行解耦
while True:
msg = await msg_queue.get()
# 推送 SSE
yield json.dumps(msg)
if msg.get("type") == "done":
break
@app.post("/stream")
async def stream_data():
return StreamingResponse(generate_data(), media_type="text/plain")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)