新版的Fastapi框架改变的原先的生命周期管理方式,使用 lifespan 参数和上下文管理器来管理web项目启停的生命周期。
旧版的方式如下:

from fastapi import FastAPI
 
app = FastAPI()
 
# 应用程序启动时执行的函数
@app.on_event("startup")
async def startup_event():
    print("应用程序启动...")
    # 在这里可以进行数据库连接,启动线程,或其他初始化操作
 
# 应用程序关闭时执行的函数
@app.on_event("shutdown")
async def shutdown_event():
    print("应用程序关闭...")
    # 在这里可以进行清理操作,如关闭数据库连接,停止线程
 
# 定义路由和业务逻辑
@app.get("/")
async def root():
    return {"message": "Hello World"}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

使用的是@app.on_event装饰器,参数只有startup和shutdown。新版不在推荐使用,使用期间会有警告提示:

DeprecationWarning: 
        on_event is deprecated, use lifespan event handlers instead.

        Read more about it in the
        [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).
        
  @app.on_event("shutdown")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

新版的写法(官方例子):

from contextlib import asynccontextmanager
from fastapi import FastAPI

def fake_answer_to_everything_ml_model(x: float):
    return x * 42

ml_models = {}

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Load the ML model
    ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
    yield
    # Clean up the ML models and release resources
    ml_models.clear()

app = FastAPI(lifespan=lifespan)

@app.get("/predict")
async def predict(x: float):
    result = ml_models["answer_to_everything"](x)
    return {"result": result}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.