Careeroza
Lifespan Events
Startup and Shutdown
Example
Create shared resources (DB pools, HTTP clients, ML models) once at startup and close them at shutdown:
from contextlib import asynccontextmanager
from fastapi import FastAPI
resources = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
resources["model"] = "sentiment-model-v2 loaded" # startup
yield
resources.clear() # shutdown
app = FastAPI(lifespan=lifespan)
@app.get("/model")
def model_info():
return {"model": resources["model"]}Requests and responses
GET /model
→ 200 {"model": "sentiment-model-v2 loaded"}