05.06

Middleware, CORS, and lifespan

skillmaxingPython with AIMiddleware, CORS, and lifespan
Visual lesson

Middleware, CORS, and lifespan

Included with Pro · 4:54
Lessons · 1,029 words

Some things in a service are not about any one request. The database engine and its connection pool, the httpx client that talks to the model API, the Redis connection: these are created once when the process starts and closed once when it stops. Other things are about every request equally: a request id, a timing header, a check that the calling website is allowed. FastAPI has one mechanism for each. Lifespan is a context manager that wraps the whole life of the app. Middleware is a function that wraps every request. CORS is a specific middleware that answers a question only browsers ask.

Two lifetimes
Figure 1Two lifetimesLifespan runs once at each end; middleware runs around every request in between.
# src/relay/main.py
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from relay.settings import get_settings
Pro

Continue reading

Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.

Unlock full access to
Python with AIAI researchComplete system design
30% off with LAUNCH30ends in 7h 40m
Buy now
View all plans ·Already Pro? Sign in
124 online