Overview
Uvicorn 0.21, released on March 9, 2023, introduces lifespan state allowing shared state between the application lifecycle and request handlers.
Main Features
Lifespan state
The state dictionary passed to the lifespan protocol is now injected into each request scope, making it easy to share DB connections, caches, and other resources initialized at startup.
python
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
@asynccontextmanager
async def lifespan(app):
# Startup: initialize resources
app.state.db = await create_pool()
yield
# Shutdown: close resources
await app.state.db.close()
app = FastAPI(lifespan=lifespan)
@app.get('/')
async def root(request: Request):
pool = request.state.db
return {'status': 'ok'}
