python - uvicorn 启动时执行脚本并缓存数据

标签 python python-3.x fastapi uvicorn

我正在使用 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/

相关文章:

python - 从 python 中的 json 数组访问数据

python - Argparse 与函数的交互

python - 将 FastAPI 中的请求记录到项目目录中的特定文件中

Python 多处理 : Pool of custom Processes

Python vars() 全局名称错误

python - Pandas 将数据框转换为 3d 数据

python - 读取文件并将小写和大写分开到两个不同的文件(Python)

python - 在列表中替换时遇到问题 - Python

python - 如何在 fastapi 的 pydantic 模型中允许 List 作为查询参数而不是 requestbody

python - 在 AWS App Runner 上运行的 FastAPI 服务器在 24 小时后失败