我有一个使用Uvicorn
和FastAPI
的应用程序。我还打开了一些连接(例如,到MongoDB
)。一旦出现信号,我想优雅地关闭这些连接(SIGINT
、SIGTERM
和SIGKILL
)。
我的server.py
文件:
import uvicorn
import fastapi
import signal
import asyncio
from source.gql import gql
app = fastapi.FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
app.mount("/graphql", gql)
# handle signals
HANDLED_SIGNALS = (
signal.SIGINT,
signal.SIGTERM
)
loop = asyncio.get_event_loop()
for sig in HANDLED_SIGNALS:
loop.add_signal_handler(sig, _some_callback_func)
if __name__ == "__main__":
uvicorn.run(app, port=6900)
不幸的是,我试图做到这一点的方式是行不通的。当我在终端机上尝试Ctrl+C
时,什么都不会发生。我认为是因为Uvicorn
是在不同的线程中启动的.
正确的做法是什么?我注意到了uvicorn.Server.install_signal_handlers()
函数,但使用它并不幸运.
发布于 2022-03-18 16:17:37
FastAPI允许定义在应用程序启动之前或应用程序关闭时需要执行的事件处理程序(函数)。因此,您可以使用shutdown
事件,如这里所描述的
@app.on_event("shutdown")
def shutdown_event():
# close connections here
https://stackoverflow.com/questions/71528875
复制相似问题