Trung BìnhPython iconPython

Middleware trong FastAPI — viết custom middleware thế nào?

Middleware chạy trước và sau mỗi request.

Dùng @app.middleware("http") cho custom middleware.

python
import time, uuid
from fastapi import Request

@app.middleware("http")
async def logging_middleware(request: Request, call_next):
    request_id = str(uuid.uuid4())
    start = time.perf_counter()

    response = await call_next(request)

    duration = time.perf_counter() - start
    response.headers["X-Request-ID"] = request_id
    response.headers["X-Duration"] = f"{duration:.4f}"
    return response

CORS, GZip, TrustedHost — dùng built-in middlewares.

Pitfall: Middleware exception handler không bắt HTTP exceptions từ path operations — dùng exception_handler thay.

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python