第 10 章: 中间件介绍


本章概述

学习如何使用中间件拦截请求并在请求前或响应后执行操作。


10.1 创建中间件

from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    import time
    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

10.2 中间件的应用场景

  • 记录请求日志
  • 添加CORS头
  • 身份验证
  • 请求限流
  • 错误处理

10.3 CORS中间件

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

10.4 自定义中间件示例

记录所有请求:

import time
from fastapi import Request

@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()
    
    response = await call_next(request)
    
    process_time = time.time() - start_time
    print(f"{request.method} {request.url} - {response.status_code} ({process_time:.2f}s)")
    
    return response

小结

在本章中,我们学习了: - ✅ 创建中间件 - ✅ 在请求前和响应后执行代码 - ✅ 中间件的常见应用场景 - ✅ 配置CORS中间件 - ✅ 创建自定义日志中间件

在下一章中,我们将学习用户认证!