0%

FastAPI自学教程(55) - 响应头配置

1.基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse

app = FastAPI()

# 方法一:通过Response参数设置
@app.get("/headers-and-object/")
def get_headers(response: Response):
response.headers["X-Custom-Header"] = "value"
return {"message": "Header set via parameter"}

# 方法二:直接返回响应对象
@app.get("/direct-headers/")
def get_direct_headers():
content = {"message": "Header set directly"}
headers = {"X-Another-Header": "direct_value"}
return JSONResponse(content=content, headers=headers)
  • 两种设置方式对比:
    graph TD
      A[客户端请求] --> B{设置方式}
      B -->|Response参数| C[创建临时响应对象]
      B -->|直接返回| D[构建完整响应对象]
      C --> E[修改headers字典]
      D --> F[传递headers参数]
      E & F --> G[返回最终响应]

2.进阶配置

2.1 自定义专有头部

1
response.headers["X-API-Version"] = "v2.3.1"  # 符合X-前缀规范
  • 浏览器可见性要求:需在CORS配置中添加expose_headers参数
  • 安全规范建议:
    • 敏感头信息使用HTTPS传输(secure=True
    • 设置httponly=True防止XSS攻击

2.2 组合配置技巧

1
2
3
4
5
6
7
@app.get("/secure-headers")
def security_headers(response: Response):
response.headers.update({
"Strict-Transport-Security": "max-age=31536000",
"Content-Security-Policy": "default-src 'self'"
})
return {"status": "security headers added"}
  • 推荐安全头部组合:
    • HSTS强制HTTPS
    • CSP内容安全策略
    • X-Content-Type-Options防MIME嗅探

3.技术细节

3.1 框架实现原理

  • fastapi.Response本质继承自starlette.responses.Response
  • 响应处理流程:
    1. 路径函数返回原始数据
    2. 通过jsonable_encoder序列化
    3. 合并临时响应对象中的headers

3.2 响应类型扩展

1
from starlette.responses import Response  # 支持原生Starlette响应
  • 兼容性说明:
    • 所有Starlette响应类型可直接使用
    • FastAPI额外提供ORJSONResponse等优化类型

测试命令示例:

1
curl -i http://localhost:8000/headers-and-object/