0%

FastAPI自学教程(64) - 代理服务器配置

1.基础用法

1
2
3
4
5
6
7
from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/app")
async def read_main(request: Request):
return {"root_path": request.scope.get("root_path")}
  • 通过--root-path命令行参数或FastAPI(root_path="/api/v1")设置根路径,解决代理服务器剥离路径前缀的问题
  • 请求处理流程:
    graph LR
      A[浏览器访问 /api/v1/app] --> B[代理服务器]
      B -->|剥离/api/v1前缀| C[FastAPI应用处理/app]
      C --> D[返回响应时自动添加前缀]

2.核心机制

2.1 root_path原理

  • ASGI规范通过scope["root_path"]传递路径前缀信息,代理服务器与FastAPI应用间路径映射的桥梁
  • 应用开发时无需感知代理路径,保持代码路径与直接运行时一致

2.2 文档适配

1
2
3
4
app = FastAPI(
openapi_url="/api/v1/openapi.json",
docs_url="/api/v1/docs"
)
  • OpenAPI文档自动继承代理路径前缀,确保前端正确加载资源
  • 生成OpenAPI Schema时自动添加servers字段声明代理路径

3.生产环境配置

3.1 Traefik示例

1
2
3
# Traefik配置剥离/api/v1前缀
[http.middlewares.api-stripprefix.stripPrefix]
prefixes = ["/api/v1"]
  • 本地测试可通过Traefik实现路径前缀剥离,验证代理配置
  • 启动命令需同步设置root_path:
    1
    uvicorn main:app --root-path /api/v1

3.2 安全增强

  • 强制HTTPS传输时配置X-Forwarded-Proto头识别原始协议
  • 通过中间件验证X-Forwarded-For客户端真实IP

4.调试与监控

1
2
3
4
5
6
@app.get("/debug")
async def debug(request: Request):
return {
"root_path": request.scope["root_path"],
"headers": dict(request.headers)
}
  • 实时查看代理传递的路径前缀和请求头信息
  • 结合Prometheus监控代理路径的请求响应时间

测试命令示例:

1
2
3
4
5
# 带root_path启动
uvicorn main:app --root-path /api/v1

# 测试路径映射
curl http://localhost:8000/app