import time import logging from typing import Callable from fastapi import FastAPI, Request, Response from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.trustedhost import TrustedHostMiddleware from starlette.middleware.base import BaseHTTPMiddleware logger = logging.getLogger(__name__) class ProcessTimeMiddleware(BaseHTTPMiddleware): """Middleware to log request processing time.""" async def dispatch(self, request: Request, call_next: Callable) -> Response: start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers["X-Process-Time"] = str(process_time) # Log request details and processing time logger.info( f"{request.method} {request.url.path} {response.status_code} " f"Processed in {process_time:.4f} seconds" ) return response def setup_middlewares(app: FastAPI) -> None: """Set up all middlewares for the application.""" # Add CORS middleware first app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Add trusted host middleware app.add_middleware( TrustedHostMiddleware, allowed_hosts=["*"] ) # Add custom processing time middleware app.add_middleware(ProcessTimeMiddleware)