FastAPI系列:应用启动和关闭事件
应用启动和关闭事件(旧版本)
事件处理程序,在应用程序启动之前和关闭期间执行。每次uvicorn和hypercorn服务器重启加载时都会激活这些事件
app = FastAPI()
# 启动事件
@app.on_event("startup")
async def initialize(request: Request):
request.state.engine = await db.set_bind("mysql+mysqldb://root:123456@localhost/foo")
# 关闭事件
@app.on_event("shutdown")
async def destory(request: Request):
await request.state.engine.close()
应用启动和关闭事件(新版本)
新版本推荐使用lifespan+异步上下文
from contextlib import asynccontextmanager
app = FastAPI()
@asynccontextmanager
async def lifespan(app: FastAPI, request: Request):
request.state.engine = await db.set_bind("mysql+mysqldb://root:123456@localhost/foo")
yield
await request.state.engine.close()
app = FastAPI(lifespan=lifespan)
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!