0%

FastAPI自学教程(67) - 生命周期事件

1.基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from contextlib import asynccontextmanager
from fastapi import FastAPI

def load_ml_model():
return "pretrained_model"

@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时加载资源
app.state.ml_model = load_ml_model()
yield
# 关闭时释放资源
del app.state.ml_model

app = FastAPI(lifespan=lifespan)

@app.get("/predict")
async def predict():
return {"model": app.state.ml_model}
  • 使用@asynccontextmanager创建异步上下文管理器定义生命周期
  • yield前代码在应用启动前执行(如加载模型/数据库连接池)
  • yield后代码在应用关闭时执行(如释放GPU资源/关闭连接)
  • 流程图展示生命周期处理流程:
    graph TD
      A[应用启动] --> B[执行yield前代码]
      B --> C[接收请求]
      C --> D[处理业务逻辑]
      D --> E[应用关闭]
      E --> F[执行yield后代码]

2.进阶配置

2.1 旧版事件方法(已弃用)

1
2
3
4
5
6
7
@app.on_event("startup")
async def startup_event():
print("应用启动")

@app.on_event("shutdown")
async def shutdown_event():
print("应用关闭")
  • 注意:该方式与新的lifespan参数互斥,不可同时使用

2.2 多层资源管理

1
2
3
4
5
6
7
8
9
10
11
@asynccontextmanager 
async def complex_lifespan(app: FastAPI):
# 初始化数据库
await init_database()
# 加载缓存
app.state.cache = RedisPool()
yield
# 关闭缓存
await app.state.cache.close()
# 清理数据库
await cleanup_database()
  • 支持嵌套初始化多个依赖资源
  • 确保关闭顺序与初始化顺序相反(后进先出)

3.生产环境建议

  1. 数据库管理

    • 初始化时建立连接池,关闭时安全释放连接
      1
      2
      3
      4
      async def lifespan(app: FastAPI):
      app.state.db = await create_pool()
      yield
      await app.state.db.disconnect()
  2. 性能优化

    • 避免在启动阶段加载超大文件(超过5GB建议延迟加载)
    • 使用app.state存储全局共享对象
  3. 错误处理

    1
    2
    3
    4
    5
    6
    7
    @asynccontextmanager
    async def safe_lifespan(app: FastAPI):
    try:
    init_resources()
    yield
    finally:
    release_resources()
    • 使用try/finally确保资源释放

测试命令示例:

1
2
# 带生命周期配置启动
uvicorn main:app --root-path /api/v1