缘起假如你用 FastAPI/Starlette框架,写了一段Server-sent Events@app.get('/api/my_stream')
async def api_stream():
async def gen():
while 1:
yield "data: {}\n\n"
await asyncio.sleep(1.0)
return StreamingResponse(gen, media_type="text/event-stream", headers={
'X-Accel-Buffering': 'no',
'Cache-Control': "no-cache",
'Connection': "keep-alive",
})FastAPI 事件然后你重启了服务器,比如 gunicorn+uvicorn,你会发现这个连接不会断开,一直输出结果。直到 worker 进程超过配置里的timeout参数(默认60秒),被 master 强行杀死然后重启。一开始尝试了FastAPI 官方的shutdown事件,再在代码的while 1加一个if判断。发现不管用@app.on_event('shutdown')
def on_server_shutdown():
app.state.run
...
继续阅读
(120)