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)
posted @ 2024-02-28 18:14  我在路上回头看  阅读(224)  评论(0编辑  收藏  举报