Add CORS, Gzip, request logging, and timing headers via FastAPI middleware.
Middleware
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
import time
app = FastAPI()
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins = ["https://myapp.com", "https://www.myapp.com"],
allow_methods = ["*"],
allow_headers = ["*"],
allow_credentials = True,
)
# Gzip compression
app.add_middleware(GZipMiddleware, minimum_size=1000)
# Custom middleware
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
@app.middleware("http")
async def log_requests(request: Request, call_next):
print(str(request.method) + " " + str(request.url))
response = await call_next(request)
print("Status: " + str(response.status_code))
return response