FastAPI 进阶知识(六) 启动-关闭事件

作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

我们可以在应用启动和关闭的时候自定义事件处理器。注意,只有主应用才可以这么做。

启动事件

通过"startup"事件来声明一个应当在应用启动之前运行的函数。

from fastapi import FastAPI

app = FastAPI()

items = {}


@app.on_event("startup")
async def startup_event():
    items["foo"] = {"name": "Fighters"}
    items["bar"] = {"name": "Tenders"}


@app.get("/items/{item_id}")
async def read_items(item_id: str):
    return items[item_id]

我们可以添加更多的事件处理函数。

只有在处理完成所有的startup事件函数之后,应用才会开始接收请求。

关闭事件

通过"shutdown"事件来声明一个在应用退出之时运行的函数。

from fastapi import FastAPI

app = FastAPI()


@app.on_event("shutdown")
def shutdown_event():
    with open("log.txt", mode="a") as log:
        log.write("Application shutdown")


@app.get("/items/")
async def read_items():
    return [{"name": "Foo"}]

更多事件处理器可以参考:Starlette's Events' docs

原文地址:https://www.cnblogs.com/mazhiyong/p/13372006.html