我正在使用 fastapi
构建 RESTful Web 服务。为了运行该服务,我使用 uvicorn
。在 uvicorn
启动时,我想执行我的 python 脚本,该脚本将进行数据库调用并缓存一些数据,以便在 uvicorn
运行之前可以重复使用它。我尝试查找 uvicorn 的文档,但没有找到任何引用。
有什么办法可以实现我的要求吗?
最佳答案
使用 FastAPI startup
事件。来自 FastAPI docs :
from fastapi import FastAPI app = FastAPI() items = {} @app.on_event("startup") async def startup_event(): items["foo"] = {"name": "Fighters"} items["bar"] = {"name": "Tenders"}
In this case, the startup event handler function will initialize the
items
"database" (just a dict) with some values.You can add more than one event handler function.
And your application won't start receiving requests until all the startup event handlers have completed.
(此功能实际上在 starlette 中实现 - FastAPI 所基于的 ASGI 框架)
关于python - uvicorn 启动时执行脚本并缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69825687/