FastAPI中间件实战:5个自定义中间件提升你的API安全性与性能
在构建现代Web API时,开发者常常面临一个核心矛盾:如何在保持代码简洁和开发效率的同时,确保服务的安全性、健壮性和高性能?FastAPI以其出色的性能和直观的设计赢得了大量开发者的青睐,但一个真正能投入生产环境的API,往往需要在请求/响应处理流水线中注入一系列“守卫”和“优化器”。这就是中间件的用武之地。
对于中高级开发者而言,仅仅使用框架内置的中间件可能不足以应对复杂的业务场景和安全挑战。自定义中间件提供了一种强大而灵活的手段,允许你在请求抵达路由处理器之前,以及在响应返回给客户端之后,插入自定义的逻辑。这就像是为你的API装配了一套可编程的“神经系统”,能够精细地控制流量、记录行为、加固防线并优化输出。本文将深入实战,为你呈现5个可直接复用的自定义中间件实现方案,它们分别针对API限流、精细化日志、统一错误处理、安全头注入和智能响应压缩这些关键需求。我们将从原理剖析到代码实现,再到生产环境中的注意事项,手把手带你构建更安全、更高效的FastAPI应用。
1. 构建坚不可摧的第一道防线:智能限流中间件
API无限制地被调用是服务稳定性的噩梦。恶意爬虫、客户端bug或是突发的流量洪峰,都可能瞬间击垮你的后端服务。限流(Rate Limiting)是保护API免受滥用和保证服务可用性的基石。一个优秀的限流中间件不应只是简单地计数,它需要兼顾灵活性、公平性和对用户体验的最小影响。
1.1 基于令牌桶算法的自适应限流
我们首先实现一个基于令牌桶算法的限流中间件。与简单的固定窗口计数器相比,令牌桶算法允许一定程度的突发流量,更加平滑,也更符合实际业务场景。
import time
from collections import defaultdict
from typing import Dict, Tuple
from fastapi import FastAPI, Request, HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
class TokenBucketRateLimiter:
"""令牌桶限流器实现"""
def __init__(self, capacity: int, fill_rate: float):
"""
Args:
capacity: 桶的容量(最大令牌数)
fill_rate: 每秒填充的令牌数
"""
self.capacity = capacity
self.fill_rate = fill_rate
self.tokens = capacity
self.last_fill = time.time()
def _add_tokens(self):
"""根据时间流逝向桶中添加令牌"""
now = time.time()
delta = now - self.last_fill
new_tokens = delta * self.fill_rate
if new_tokens > 0:
self.tokens = min(self.capacity, self.tokens + new_tokens)
self.last_fill = now
def consume(self, tokens=1) -> bool:
"""尝试消费指定数量的令牌,成功返回True,否则返回False"""
self._add_tokens()
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
class AdaptiveRateLimitMiddleware(BaseHTTPMiddleware):
"""
自适应限流中间件
支持基于客户端IP和API路径的差异化限流策略
"""
def __init__(self, app, default_capacity: int = 10, default_fill_rate: float = 1.0):
super().__init__(app)
self.default_capacity = default_capacity
self.default_fill_rate = default_fill_rate
# 使用嵌套字典存储不同客户端和路径的限流器
self.buckets: Dict[str, Dict[str, TokenBucketRateLimiter]] = defaultdict(dict)
def _get_client_identifier(self, request: Request) -> str:
"""获取客户端标识,优先使用X-Forwarded-For,否则使用client.host"""
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
# 取第一个IP(最原始的客户端IP)
client_ip = forwarded.split(",")[0].strip()
else:
client_ip = request.client.host if request.client else "unknown"
return client_ip
def _get_rate_limiter(self, client_id: str, path: str) -> TokenBucketRateLimiter:
"""获取或创建指定客户端和路径的限流器"""
if path not in self.buckets[client_id]:
# 这里可以根据路径动态调整限流策略,例如对`/api/admin/`更宽松
if path.startswith("/api/admin"):
capacity, fill_rate = 50, 5.0 # 管理接口更高限额
elif path.startswith("/api/public"):
capacity, fill_rate = 2, 0.2 # 公开接口更严格
else:
capacity, fill_rate = self.default_capacity, self.default_fill_rate
self.buckets[client_id][path] = TokenBucketRateLimiter(capacity, fill_rate)
return self.buckets[client_id][path]
async def dispatch(self, request: Request, call_next):
client_id = self._get_client_identifier(request)
path = request.url.path
limiter = self._get_rate_limiter(client_id, path)
if not limiter.consume():
# 触发限流时,在响应头中告知客户端限制信息
retry_after = int((1 / limiter.fill_rate) + 0.5) # 估算重试时间(秒)
headers = {
"X-RateLimit-Limit": str(limiter.capacity),
"X-RateLimit-Remaining": str(int(limiter.tokens)),
"X-RateLimit-Reset": str(int(time.time() + (1 / limiter.fill_rate))),
"Retry-After": str(retry_after)
}
return JSONResponse(
status_code=429,
content={
"detail": "请求过于频繁,请稍后再试。",
"retry_after": retry_after
},
headers=headers
)
# 在响应头中添加当前限流状态信息
response = await call_next(request)
response.headers["X-RateLimit-Limit"] = str(limiter.capacity)
response.headers["X-RateLimit-Remaining"] = str(int(limiter.tokens))
return response
注意:上述实现将状态存储在内存中,适用于单进程部署。在生产环境的分布式系统中,你需要将令牌桶的状态存储到Redis等共享存储中,以确保所有服务实例的限流计数一致。
1.2 中间件集成与策略配置
将限流中间件集成到FastAPI应用时,顺序很重要。通常,限流应该是请求处理链中较早的一环,以避免无效请求消耗过多后端资源。
from fastapi import FastAPI
app = FastAPI(title="受保护的API服务")
# 添加限流中间件,建议放在其他中间件之前(安全头中间件之后)
app.add_middleware(
AdaptiveRateLimitMiddleware,
default_capacity=20, # 默认桶容量:20个请求
default_fill_rate=2.0 # 默认填充速率:每秒2个令牌
)
@app.get("/api/data")
async def get_data():
return {"data": "这是受限流保护的数据接口"}
@app.get("/api/admin/dashboard")
async def admin_dashboard():
return {"message": "管理员仪表板,拥有更高的限流额度"}
这个中间件不仅阻止了过量请求,还通过响应头X-RateLimit-*向合规的客户端提供了透明的配额信息,这是一种良好的API设计实践。
2. 洞察每一个请求:结构化日志与性能追踪中间件
日志是系统的眼睛。然而,简单的print语句或零散的日志输出在排查复杂问题时往往力不从心。一个强大的日志中间件应该能自动为每个请求生成结构化的上下文信息,并方便地与像ELK、Loki这样的日志聚合系统集成。
2.1 生成请求上下文与全链路追踪
我们将创建一个中间件,它不仅记录请求的基本信息,还生成唯一的请求ID,并追踪在中间件链和路由处理中花费的时间。
import logging
import time
import uuid
from contextvars import ContextVar
from typing import Optional
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
import json
# 使用ContextVar来存储请求上下文,确保在异步环境中数据隔离
_request_id_ctx: ContextVar[Optional[str]] = ContextVar("request_id", default=None)
_request_start_time_ctx: ContextVar[Optional[float]] = ContextVar("request_start_time", default=None)
# 配置结构化日志的JSON格式器
class StructuredJsonFormatter(logging.Formatter):
def format(self, record):
log_object = {
"timestamp": self.formatTime(record),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
"request_id": getattr(record, 'request_id', None),
"client_ip": getattr(record, 'client_ip', None),
"user_agent": getattr(record, 'user_agent', None),
"path": getattr(record, 'path', None),
"method": getattr(record, 'method', None),
"status_code": getattr(record, 'status_code', None),
"response_time_ms": getattr(record, 'response_time_ms', None),
}
# 合并任何额外的结构化数据
if hasattr(record, 'extra'):
log_object.update(record.extra)
return json.dumps(log_object, ensure_ascii=False)
# 配置日志处理器
logger = logging.getLogger("api")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(StructuredJsonFormatter())
logger.addHandler(handler)
class StructuredLoggingMiddleware(BaseHTTPMiddleware):
"""结构化日志与性能追踪中间件"""
async def dispatch(self, request: Request, call_next):
# 生成唯一请求ID
request_id = str(uuid.uuid4())
_request_id_ctx.set(request_id)
start_time = time.time()
_request_start_time_ctx.set(start_time)
# 提取客户端信息
client_ip = request.client.host if request.client else None
user_agent = request.headers.get("user-agent")
# 将请求ID存入request.state,供后续处理使用
request.state.request_id = request_id
# 在请求头中添加请求ID,便于前端追踪
request.headers.__dict__["_list"].append((b"x-request-id", request_id.encode()))
# 记录请求开始日志
logger.info(
"请求开始",
extra={
"request_id": request_id,
"client_ip": client_ip,
"user_agent": user_agent,
"path": request.url.path,
"method": request.method,
"query_params": dict(request.query_params),
}
)
try:
response = await call_next(request)
process_time = (time.time() - start_time) * 1000 # 转换为毫秒
# 记录请求完成日志
logger.info(
"请求完成",
extra={
"request_id": request_id,
"status_code": response.status_code,
"response_time_ms": round(process_time, 2),
"path": request.url.path,
}
)
# 在响应头中返回请求ID和处理时间
response.headers["X-Request-ID"] = request_id
response.headers["X-Process-Time-MS"] = f"{process_time:.2f}"
return response
except Exception as exc:
process_time = (time.time() - start_time) * 1000
# 记录异常日志
logger.error(
"请求处理异常",
extra={
"request_id": request_id,
"exception_type": exc.__class__.__name__,
"exception_message": str(exc),
"response_time_ms": round(process_time, 2),
},
exc_info=True # 包含完整的异常堆栈信息
)
raise # 重新抛出异常,由错误处理中间件或框架处理
# 一个工具函数,方便在应用其他部分记录带请求上下文的日志
def log_with_context(level: str, message: str, **extra):
"""记录附带当前请求上下文的日志"""
log_data = {
"request_id": _request_id_ctx.get(),
**extra
}
log_method = getattr(logger, level)
log_method(message, extra=log_data)
2.2 在业务逻辑中使用上下文日志
现在,在你的路由处理函数中,你可以轻松地记录与当前请求相关的业务日志。
from fastapi import APIRouter, Depends, BackgroundTasks
from .some_service import process_order
router = APIRouter()
@router.post("/api/orders")
async def create_order(order_data: dict, background_tasks: BackgroundTasks):
# 使用我们的工具函数记录业务日志
log_with_context("info", "开始创建订单", order_id=order_data.get("id"))
try:
result = await process_order(order_data)
log_with_context("info", "订单处理成功", order_id=result["id"])
return result
except ValueError as e:
log_with_context("warning", "订单数据验证失败", error=str(e))
raise HTTPException(status_code=400, detail=str(e))
这种结构化的日志输出,在Kibana或Grafana中可以直接被解析和查询,极大地提升了运维和调试效率。例如,你可以轻松地查询“所有处理时间超过500毫秒的POST请求”或“某个特定用户产生的所有错误”。
3. 优雅地应对意外:全局异常处理与标准化响应中间件
在Web API中,错误处理不仅仅是返回一个状态码。一个设计良好的错误响应应该为客户端提供清晰的、可操作的指引,同时避免泄露敏感的系统信息。自定义异常处理中间件可以统一所有未捕获异常的响应格式,并安全地记录错误细节。
3.1 定义业务异常与标准化错误响应
首先,我们定义一些自定义的业务异常类和一个标准的错误响应模型。
from typing import Any, Dict, Optional
from pydantic import BaseModel
class APIError(Exception):
"""基础API异常类"""
def __init__(self, message: str, status_code: int = 500, error_code: Optional[str] = None, details: Optional[Any] = None):
self.message = message
self.status_code = status_code
self.error_code = error_code
self.details = details
super().__init__(self.message)
class ValidationError(APIError):
"""数据验证错误"""
def __init__(self, message: str, details: Optional[Dict] = None):
super().__init__(message, status_code=400, error_code="VALIDATION_ERROR", details=details)
class ResourceNotFoundError(APIError):
"""资源未找到错误"""
def __init__(self, resource_type: str, resource_id: Any):
message = f"{resource_type} '{resource_id}' 未找到"
super().__init__(message, status_code=404, error_code="RESOURCE_NOT_FOUND")
class UnauthorizedError(APIError):
"""未授权访问错误"""
def __init__(self, message: str = "认证失败或权限不足"):
super().__init__(message, status_code=401, error_code="UNAUTHORIZED")
class StandardErrorResponse(BaseModel):
"""标准错误响应模型"""
success: bool = False
error: str
error_code: Optional[str] = None
details: Optional[Any] = None
request_id: Optional[str] = None
timestamp: str
class Config:
schema_extra = {
"example": {
"success": False,
"error": "请求参数无效",
"error_code": "VALIDATION_ERROR",
"details": {"field": "email", "issue": "格式不正确"},
"request_id": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2023-10-27T10:30:00Z"
}
}
3.2 实现全局异常处理中间件
接下来,我们实现中间件来捕获所有未处理的异常,并将其转换为标准化的错误响应。
import traceback
from datetime import datetime, timezone
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
class GlobalExceptionHandlerMiddleware(BaseHTTPMiddleware):
"""全局异常处理中间件"""
async def dispatch(self, request: Request, call_next):
try:
return await call_next(request)
except HTTPException as http_exc:
# 处理FastAPI显式抛出的HTTPException
return self._make_error_response(
request,
status_code=http_exc.status_code,
message=http_exc.detail,
error_code="HTTP_ERROR"
)
except APIError as api_exc:
# 处理我们自定义的业务异常
return self._make_error_response(
request,
status_code=api_exc.status_code,
message=api_exc.message,
error_code=api_exc.error_code,
details=api_exc.details
)
except Exception as exc:
# 处理所有其他未预期的异常
# 在生产环境中,这里应该将详细的错误信息记录到内部日志系统(如Sentry),而不是返回给客户端
error_id = str(uuid.uuid4())
self._log_unexpected_error(error_id, exc, request)
# 对客户端返回一个通用的错误信息,避免泄露内部细节
return self._make_error_response(
request,
status_code=500,
message="服务器内部错误,请稍后重试。",
error_code="INTERNAL_SERVER_ERROR",
details={"error_id": error_id} if request.app.debug else None # 仅在调试模式返回错误ID
)
def _make_error_response(self, request: Request, status_code: int, message: str,
error_code: Optional[str] = None, details: Optional[Any] = None) -> JSONResponse:
"""构建标准化的错误JSON响应"""
error_response = StandardErrorResponse(
error=message,
error_code=error_code,
details=details,
request_id=getattr(request.state, 'request_id', None),
timestamp=datetime.now(timezone.utc).isoformat()
)
return JSONResponse(
status_code=status_code,
content=error_response.dict(exclude_none=True) # 排除值为None的字段
)
def _log_unexpected_error(self, error_id: str, exc: Exception, request: Request):
"""记录未预期的异常到错误追踪系统"""
# 这里可以集成Sentry, Loggly等
error_info = {
"error_id": error_id,
"exception_type": exc.__class__.__name__,
"exception_message": str(exc),
"traceback": traceback.format_exc(),
"request_path": request.url.path,
"request_method": request.method,
"client_ip": request.client.host if request.client else None,
"request_id": getattr(request.state, 'request_id', None),
}
# 在实际项目中,这里应该调用你的错误监控服务
logger.error(f"未捕获的异常: {error_id}", extra=error_info, exc_info=True)
3.3 在路由中使用自定义异常
现在,你可以在业务代码中抛出清晰的自定义异常,中间件会自动处理它们。
from fastapi import APIRouter, Query
from .models import User
router = APIRouter()
@router.get("/api/users/{user_id}")
async def get_user(user_id: int):
user = await User.get(user_id)
if not user:
# 抛出我们自定义的“资源未找到”异常
raise ResourceNotFoundError(resource_type="用户", resource_id=user_id)
return user
@router.post("/api/users")
async def create_user(user_data: dict):
# 模拟业务验证
if not user_data.get("email") or "@" not in user_data["email"]:
raise ValidationError(
"邮箱格式无效",
details={"field": "email", "expected": "有效的电子邮件地址"}
)
# ... 创建用户的逻辑
这个中间件确保了无论API内部发生什么类型的错误,客户端收到的都是结构一致、信息明确且安全的响应,极大地提升了API的可靠性和可维护性。
4. 主动安全加固:动态安全头与内容安全策略中间件
安全头(Security Headers)是Web应用安全的重要防线,它们指示浏览器如何与你的页面交互,从而缓解多种常见的攻击,如跨站脚本(XSS)、点击劫持等。一个动态的安全头中间件可以根据请求上下文智能地设置这些头信息。
4.1 实现动态安全头注入
我们将创建一个中间件,它不仅设置静态的安全头,还能根据响应内容类型、路径等因素进行动态调整。
from typing import Set, List
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""动态安全头注入中间件"""
def __init__(self, app, strict_csp: bool = True, report_only: bool = False):
super().__init__(app)
self.strict_csp = strict_csp
self.report_only = report_only # 如果为True,CSP头将使用`Content-Security-Policy-Report-Only`
async def dispatch(self, request: Request, call_next) -> Response:
response = await call_next(request)
# 1. 基础安全头(对所有响应生效)
base_headers = {
"X-Content-Type-Options": "nosniff", # 禁止MIME类型嗅探
"X-Frame-Options": "DENY", # 禁止页面被嵌入frame,防点击劫持
"Referrer-Policy": "strict-origin-when-cross-origin", # 控制Referer头信息
"Permissions-Policy": "geolocation=(), microphone=(), camera=()", # 限制某些浏览器功能
}
# 2. 动态生成内容安全策略(CSP)
csp_directives = self._build_csp_for_request(request, response)
csp_header_name = "Content-Security-Policy-Report-Only" if self.report_only else "Content-Security-Policy"
base_headers[csp_header_name] = csp_directives
# 3. 对于HTML响应,添加额外的安全头
content_type = response.headers.get("content-type", "").lower()
if "text/html" in content_type:
base_headers.update({
# 启用浏览器的XSS过滤,并在检测到攻击时阻止页面加载
"X-XSS-Protection": "1; mode=block",
})
# 4. 将安全头添加到响应中,注意不要覆盖已存在的头(除非明确需要)
for header, value in base_headers.items():
if header not in response.headers:
response.headers[header] = value
return response
def _build_csp_for_request(self, request: Request, response: Response) -> str:
"""根据请求和响应动态构建内容安全策略字符串"""
directives = []
# 默认策略:只允许从相同源加载资源
default_src = ["'self'"]
# 根据路径或响应类型放宽策略
path = request.url.path
content_type = response.headers.get("content-type", "").lower()
# 示例:对管理后台允许内联样式和脚本(仅用于演示,生产环境应谨慎)
if path.startswith("/admin/"):
# 警告:`unsafe-inline`和`unsafe-eval`是安全隐患,应尽量避免
script_src = ["'self'", "'unsafe-inline'", "'unsafe-eval'"]
style_src = ["'self'", "'unsafe-inline'"]
# 对API端点,通常不需要加载任何外部资源
elif path.startswith("/api/"):
script_src = ["'none'"]
style_src = ["'none'"]
default_src = ["'none'"] # API不应加载任何资源
# 对公共前端页面,允许从可信CDN加载资源
else:
script_src = ["'self'", "https://cdn.example.com"]
style_src = ["'self'", "https://cdn.example.com"]
# 允许图片从任何HTTPS源加载(常见于用户生成内容)
img_src = ["'self'", "https:", "data:"]
directives.append(f"img-src {' '.join(img_src)}")
# 构建指令列表
directives.append(f"default-src {' '.join(default_src)}")
directives.append(f"script-src {' '.join(script_src)}")
directives.append(f"style-src {' '.join(style_src)}")
directives.append("object-src 'none'") # 禁止Flash等插件
directives.append("base-uri 'self'") # 限制<base>标签的URL
directives.append("form-action 'self'") # 限制表单提交的目标
# 如果启用了严格模式,添加更多限制
if self.strict_csp:
directives.append("upgrade-insecure-requests") # 将HTTP自动升级为HTTPS
directives.append("block-all-mixed-content") # 阻止混合内容(HTTPS中的HTTP)
return "; ".join(directives)
4.2 集成与报告监控
将安全头中间件添加到你的应用中。在生产环境中,建议先使用report_only=True模式部署CSP,观察是否有合法的资源被策略阻止,然后再切换到强制执行模式。
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# 添加安全头中间件。注意顺序:安全头中间件通常应放在其他中间件之后、响应发送之前。
# 这样它可以基于最终的响应内容(如Content-Type)来调整策略。
app.add_middleware(SecurityHeadersMiddleware, strict_csp=True, report_only=False)
# 托管静态文件(如图片、JS、CSS)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def read_root():
return {"message": "Hello World"}
@app.get("/admin/dashboard")
async def admin_dashboard():
# 这个页面的CSP策略会更宽松(根据中间件逻辑)
return """
<html>
<head><title>Admin</title></head>
<body><h1>Admin Dashboard</h1></body>
</html>
"""
为了监控CSP违规,你还可以配置一个报告端点,让浏览器将策略违规行为报告给你的服务器。
from pydantic import BaseModel
from fastapi import APIRouter
router = APIRouter()
class CSPReport(BaseModel):
"""CSP违规报告模型"""
# 根据CSP报告规范定义字段
blocked_uri: str
disposition: str
document_uri: str
effective_directive: str
original_policy: str
referrer: str = None
status_code: int
violated_directive: str
@router.post("/_/csp-report")
async def receive_csp_report(report: CSPReport):
"""接收浏览器发送的CSP违规报告"""
# 这里应将报告记录到日志或安全事件管理系统中
logger.warning(
"CSP策略违规",
extra={
"blocked_uri": report.blocked_uri,
"document_uri": report.document_uri,
"violated_directive": report.violated_directive,
}
)
return {"status": "received"}
然后,更新中间件中的CSP指令,加入报告端点:
# 在_build_csp_for_request方法的directives列表末尾添加
directives.append(f"report-uri /_/csp-report")
这个安全头中间件为你的API穿上了一层可定制的“盔甲”,能有效抵御一大类常见的Web攻击。
5. 优化网络传输:智能响应压缩与缓存中间件
对于传输大量文本数据(如JSON、HTML)的API,启用压缩可以显著减少网络带宽使用,加快客户端加载速度。同样,合理的缓存策略能减少重复计算和数据库查询,提升性能。我们将创建一个组合中间件,根据响应内容智能地决定是否压缩,并设置合适的缓存头。
5.1 实现智能压缩与缓存逻辑
这个中间件会检查响应内容类型、大小以及客户端的支持情况,来决定是否进行GZIP或Brotli压缩。同时,它会为静态资源和可缓存的API响应设置HTTP缓存头。
import gzip
import brotli
from typing import Optional
from fastapi import Request
from fastapi.responses import Response
from starlette.middleware.base import BaseHTTPMiddleware
import mimetypes
class CompressionCacheMiddleware(BaseHTTPMiddleware):
"""智能响应压缩与缓存中间件"""
# 支持压缩的MIME类型
COMPRESSIBLE_TYPES = {
"text/html", "text/plain", "text/css", "text/javascript",
"application/json", "application/javascript", "application/xml",
"application/xhtml+xml", "application/atom+xml", "application/rss+xml"
}
# 默认应进行长期缓存的路径前缀(静态资源)
CACHEABLE_PATHS = {"/static/", "/assets/", "/images/", "/favicon.ico"}
def __init__(self, app,
min_size_to_compress: int = 500,
enable_brotli: bool = True,
default_cache_max_age: int = 3600):
super().__init__(app)
self.min_size_to_compress = min_size_to_compress
self.enable_brotli = enable_brotli
self.default_cache_max_age = default_cache_max_age
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
# 1. 处理缓存头
response = self._apply_cache_headers(request, response)
# 2. 处理压缩
response = await self._apply_compression(request, response)
return response
def _apply_cache_headers(self, request: Request, response: Response) -> Response:
"""根据请求路径和响应类型设置缓存控制头"""
path = request.url.path
content_type = response.headers.get("content-type", "").split(";")[0]
# 检查是否为可缓存的静态资源
is_cacheable_path = any(path.startswith(prefix) for prefix in self.CACHEABLE_PATHS)
is_cacheable_by_type = content_type in {
"text/css", "application/javascript", "image/", "font/", "video/"
}
# 对于可缓存的资源,设置积极的缓存策略
if is_cacheable_path or is_cacheable_by_type:
# 公共缓存,最大年龄1小时,允许代理和浏览器缓存
response.headers["Cache-Control"] = f"public, max-age={self.default_cache_max_age}"
# 设置ETag用于条件请求(这里使用简化的哈希,生产环境应用更健壮的方法)
import hashlib
if response.body:
etag = hashlib.md5(response.body).hexdigest()
response.headers["ETag"] = f'"{etag}"'
else:
# 对于动态API响应,通常建议不缓存或仅进行短期缓存
# 可以根据响应状态码进一步细化策略
if response.status_code == 200 and request.method == "GET":
# 对成功的GET请求,允许客户端和代理进行短期缓存(如10秒)
response.headers["Cache-Control"] = "public, max-age=10, must-revalidate"
else:
# 确保不缓存
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
async def _apply_compression(self, request: Request, response: Response) -> Response:
"""根据客户端支持和响应内容决定是否压缩响应体"""
# 检查客户端支持的编码
accept_encoding = request.headers.get("accept-encoding", "").lower()
# 检查响应是否适合压缩
if not self._should_compress(response):
return response
# 获取原始响应体
body = response.body
if not body:
return response
# 选择压缩算法(优先Brotli,其次GZIP)
encoding = None
compressed_body = None
if self.enable_brotli and "br" in accept_encoding and len(body) > self.min_size_to_compress:
try:
compressed_body = brotli.compress(body)
encoding = "br"
except Exception:
pass # 如果Brotli压缩失败,回退到GZIP
if not encoding and "gzip" in accept_encoding and len(body) > self.min_size_to_compress:
try:
compressed_body = gzip.compress(body)
encoding = "gzip"
except Exception:
pass
# 如果压缩成功且体积确实减小了,则使用压缩后的内容
if encoding and compressed_body and len(compressed_body) < len(body):
response.body = compressed_body
response.headers["Content-Encoding"] = encoding
response.headers["Content-Length"] = str(len(compressed_body))
# 添加Vary头,告知缓存系统响应内容会根据Accept-Encoding变化
vary = response.headers.get("vary")
if vary:
if "accept-encoding" not in vary.lower():
response.headers["Vary"] = vary + ", Accept-Encoding"
else:
response.headers["Vary"] = "Accept-Encoding"
return response
def _should_compress(self, response: Response) -> bool:
"""判断响应是否适合压缩"""
# 检查状态码:通常只压缩成功的响应
if response.status_code not in (200, 201, 202):
return False
# 检查内容类型
content_type = response.headers.get("content-type", "").split(";")[0]
if content_type not in self.COMPRESSIBLE_TYPES:
# 对于已知的不可压缩类型(如图片、视频),直接跳过
if any(content_type.startswith(prefix) for prefix in ["image/", "video/", "audio/", "font/"]):
return False
# 对于其他类型,可以尝试压缩,但这里保守起见先跳过
return False
# 检查是否已经压缩
if response.headers.get("content-encoding"):
return False
# 检查内容长度
content_length = response.headers.get("content-length")
if content_length and int(content_length) < self.min_size_to_compress:
return False
return True
5.2 中间件集成与性能考量
将这个中间件添加到你的FastAPI应用中。注意中间件的顺序:压缩和缓存处理应该在业务逻辑执行之后,但在安全头中间件之前或之后都可以,因为它们是修改响应体的。
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
# 添加压缩与缓存中间件。通常放在中间件链的较后位置,因为它需要访问最终的响应体和头信息。
app.add_middleware(
CompressionCacheMiddleware,
min_size_to_compress=1024, # 只压缩大于1KB的响应
enable_brotli=True, # 启用Brotli压缩(需要`brotli`库)
default_cache_max_age=86400 # 静态资源默认缓存1天
)
@app.get("/api/large-dataset")
async def get_large_dataset():
"""返回一个大的JSON数据集,这个响应会被自动压缩"""
import json
large_data = [{"id": i, "value": f"item_{i}"} for i in range(10000)]
return JSONResponse(content={"data": large_data})
@app.get("/static/config.json")
async def get_static_config():
"""模拟一个静态JSON文件,会被缓存和压缩"""
config = {"version": "1.0", "features": ["auth", "upload"]}
return JSONResponse(content=config)
在实际项目中,对于真正的静态文件(如图片、CSS、JS),你应该使用StaticFiles或通过Nginx/Apache等Web服务器来托管,它们通常能提供更高效的静态文件服务和压缩。这个中间件主要针对动态生成的API响应进行优化。
6. 中间件的组合、顺序与生产环境实践
单独使用上述任何一个中间件都能带来显著好处,但将它们组合起来,并正确安排执行顺序,才能发挥最大威力。此外,在生产环境中部署这些中间件还需要考虑一些关键因素。
6.1 中间件执行顺序的重要性
中间件的执行顺序是“洋葱模型”:先添加的中间件,其dispatch方法中await call_next(request)之前的代码最先执行,但其后的代码最后执行。这决定了它们处理请求和响应的时机。
一个推荐的中间件添加顺序如下:
from fastapi import FastAPI
app = FastAPI()
# 顺序 1: 请求ID与日志(最早处理请求,最晚记录完成时间)
app.add_middleware(StructuredLoggingMiddleware)
# 顺序 2: 全局异常处理(尽早捕获后续中间件可能抛出的异常)
app.add_middleware(GlobalExceptionHandlerMiddleware)
# 顺序 3: 安全头(应在业务逻辑执行前设置?实际上,部分安全头需要知道最终响应内容,见下文讨论)
# 注意:安全头中间件如果依赖最终响应内容(如CSP),则需要放在靠后的位置。
# 但像X-Content-Type-Options这类基础头可以早点设置。一种折中是将安全头逻辑拆分。
# 这里我们先添加一个只设置基础安全头的中间件。
app.add_middleware(BasicSecurityHeadersMiddleware)
# 顺序 4: 限流(在认证之后,业务逻辑之前进行流量控制)
app.add_middleware(AdaptiveRateLimitMiddleware, default_capacity=100, default_fill_rate=10)
# 顺序 5: 认证/授权中间件(如果有)
# app.add_middleware(AuthenticationMiddleware)
# ... 其他业务相关的中间件 ...
# 顺序 N-1: 压缩与缓存(在响应体最终确定后,发送前进行处理)
app.add_middleware(CompressionCacheMiddleware)
# 顺序 N: 最终的安全头调整(如果需要基于压缩后的内容调整CSP,可以再加一个)
# app.add_middleware(FinalSecurityHeadersMiddleware)
关于安全头中间件的位置,有一个常见的矛盾:像Content-Security-Policy这样的头可能需要知道响应内容类型(是HTML还是JSON)来动态调整策略,因此它需要在业务逻辑执行之后运行。但像X-Frame-Options这样的基础头可以早点设置。解决方案可以是拆分成两个中间件,或者在一个中间件内,将基础头设置在call_next之前,将依赖响应内容的头设置在call_next之后。
6.2 性能监控与调试
在添加了多个中间件后,监控它们的性能影响至关重要。我们可以扩展之前的日志中间件,为每个中间件的执行时间添加细粒度的追踪。
import time
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
class PerformanceMonitoringMiddleware(BaseHTTPMiddleware):
"""性能监控中间件,测量每个中间件和路由的处理时间"""
async def dispatch(self, request: Request, call_next):
# 在request.state中初始化计时器
if not hasattr(request.state, "timers"):
request.state.timers = {}
timer_key = self.__class__.__name__
start_time = time.perf_counter()
response = await call_next(request)
elapsed = time.perf_counter() - start_time
request.state.timers[timer_key] = elapsed * 1000 # 毫秒
# 将计时信息添加到响应头(仅用于调试)
if hasattr(request.state, "timers"):
timers_str = "; ".join([f"{k}:{v:.2f}ms" for k, v in request.state.timers.items()])
response.headers["X-Performance-Timers"] = timers_str
return response
然后,你需要修改其他中间件,让它们也记录自己的处理时间到request.state.timers字典中。最后,在日志中间件里,你可以将总的请求处理时间与各个中间件耗时一起记录下来,便于分析性能瓶颈。
6.3 配置管理与环境区分
在生产、测试、开发环境中,中间件的配置可能不同。例如,在开发环境你可能需要详细的日志和宽松的限流,而在生产环境则需要严格的限流和压缩。
import os
from typing import Optional
from pydantic import BaseSettings
class Settings(BaseSettings):
environment: str = "development"
enable_detailed_logging: bool = True
rate_limit_capacity: int = 100
rate_limit_fill_rate: float = 10.0
enable_response_compression: bool = True
strict_security_headers: bool = False # 生产环境应为True
class Config:
env_file = ".env"
settings = Settings()
def create_application() -> FastAPI:
app = FastAPI(title="My API", debug=(settings.environment == "development"))
# 条件添加中间件
if settings.enable_detailed_logging:
app.add_middleware(StructuredLoggingMiddleware)
app.add_middleware(GlobalExceptionHandlerMiddleware)
app.add_middleware(
AdaptiveRateLimitMiddleware,
default_capacity=settings.rate_limit_capacity,
default_fill_rate=settings.rate_limit_fill_rate
)
if settings.enable_response_compression:
app.add_middleware(CompressionCacheMiddleware)
# 安全头中间件,在生产环境使用严格模式
app.add_middleware(
SecurityHeadersMiddleware,
strict_csp=settings.strict_security_headers,
report_only=(not settings.strict_security_headers) # 非生产环境先只报告
)
return app
app = create_application()
通过环境变量来驱动中间件的配置,你可以轻松地让应用在不同环境下表现出不同的行为。
6.4 测试你的中间件
为中间件编写测试至关重要。使用FastAPI的TestClient,你可以模拟请求并验证中间件的行为。
from fastapi.testclient import TestClient
from your_main_app import app
client = TestClient(app)
def test_rate_limit_middleware():
"""测试限流中间件"""
# 在短时间内发送超过限制的请求
responses = []
for _ in range(15): # 假设限制是10次/秒
response = client.get("/api/data")
responses.append(response.status_code)
# 前10个请求应该成功,后面的应该被限流(429)
assert 200 in responses[:10]
assert 429 in responses[10:]
def test_security_headers_middleware():
"""测试安全头中间件"""
response = client.get("/")
assert response.headers["X-Content-Type-Options"] == "nosniff"
assert response.headers["X-Frame-Options"] == "DENY"
# 检查CSP头是否存在
assert "Content-Security-Policy" in response.headers or \
"Content-Security-Policy-Report-Only" in response.headers
def test_compression_middleware():
"""测试压缩中间件"""
# 请求时声明支持gzip压缩
headers = {"Accept-Encoding": "gzip, deflate, br"}
response = client.get("/api/large-dataset", headers=headers)
# 检查响应是否被压缩
if int(response.headers.get("Content-Length", 0)) > 1000: # 假设原始数据很大
assert response.headers.get("Content-Encoding") in ["gzip", "br"]
# 检查Vary头是否正确设置
assert "Accept-Encoding" in response.headers.get("Vary", "")
这些测试能确保你的中间件在各种条件下按预期工作,避免将bug带入生产环境。
构建和维护一套精心设计的自定义中间件,起初可能会花费一些时间,但它带来的回报是巨大的:更安全的API、更可靠的监控、更快的响应速度以及更一致的错误处理。随着项目规模的增长,这些中间件将成为你基础设施中不可或缺的稳定基石。
502




被折叠的 条评论
为什么被折叠?



