33 lines
868 B
Python
33 lines
868 B
Python
# main.py
|
|
import time
|
|
from fastapi import FastAPI
|
|
from fastapi.responses import StreamingResponse
|
|
|
|
app = FastAPI()
|
|
def slow_generator():
|
|
for i in range(5):
|
|
yield f"第 {i+1} 条数据\n"
|
|
time.sleep(1) # 故意慢一点,方便观察
|
|
|
|
@app.get("/non-stream")
|
|
def stream():
|
|
return StreamingResponse(
|
|
slow_generator(),
|
|
media_type="text/plain", # 先用最简单的 text/plain
|
|
)
|
|
|
|
@app.get("/stream")
|
|
def stream():
|
|
return StreamingResponse(
|
|
slow_generator(),
|
|
media_type="text/event-stream", # 关键:改成 SSE 类型
|
|
headers={
|
|
"Cache-Control": "no-cache",
|
|
"Connection": "keep-alive",
|
|
"X-Accel-Buffering": "no", # Nginx 下禁用缓冲
|
|
},
|
|
)
|
|
|
|
if __name__ == '__main__':
|
|
import uvicorn
|
|
uvicorn.run(app,host='127.0.0.1',port=8001) |