Middleware in Python
A middleware wraps every request: timing, headers, logging.
import time
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.testclient import TestClient
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["https://typestar.io"])
@app.middleware("http")
async def add_timing(request: Request, call_next):
started = time.perf_counter()
response = await call_next(request)
elapsed = (time.perf_counter() - started) * 1000
response.headers["X-Elapsed-Ms"] = f"{elapsed:.1f}"
return response
@app.get("/ping")
def ping():
return {"pong": True}
client = TestClient(app)
response = client.get("/ping")
print(response.json(), "X-Elapsed-Ms" in response.headers)
How it works
- The function receives the request and a call_next.
- Whatever it returns is the response the client gets.
- CORS is a middleware the framework ships.
Keywords and builtins used here
add_timingasyncawaitdefpingprintreturn
The run, in numbers
- Lines
- 27
- Characters to type
- 664
- Tokens
- 159
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 87 seconds.
Step 3 of 3 in Dependencies & async, step 12 of 19 in Web services & data access.