0%

FastAPI自学教程(51) - 直接返回响应

1.基础用法

1
2
3
4
5
6
7
8
9
10
11
12
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/custom-response")
async def custom_response():
return JSONResponse(
status_code=201,
content={"message": "自定义响应"},
headers={"X-Custom-Header": "value"}
)
  • 直接返回Response或子类实例(如JSONResponse
  • 核心功能:
    • 完全控制响应状态码、头部、内容
    • 绕过框架的自动响应处理流程
  • 流程对比:
    graph LR
      A[普通响应] --> B[自动序列化数据]
      A --> C[自动添加默认头]
      D[直接响应] --> E[完全手动控制]
      D --> F[支持任意格式]

2.高级配置

2.1 响应类型覆盖

1
2
3
4
5
6
7
from fastapi.responses import HTMLResponse

@app.get("/preview", response_class=HTMLResponse)
async def preview_page():
return """
<html><body><h1>HTML预览</h1></body></html>
"""
  • 通过response_class指定默认响应类型
  • 支持类型:PlainTextResponseFileResponse

2.2 流式响应

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi.responses import StreamingResponse

def generate_large_csv():
for row in range(10000):
yield f"data{row}\n"

@app.get("/stream-data")
async def stream_data():
return StreamingResponse(
generate_large_csv(),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=bigfile.csv"}
)
  • 适用大文件传输,避免内存溢出
  • 支持生成器逐步产生响应内容

3.响应头控制

1
2
3
4
5
6
7
8
from fastapi.responses import Response

@app.get("/security-headers")
async def secure_endpoint():
response = Response()
response.headers["Strict-Transport-Security"] = "max-age=31536000"
response.headers["Content-Security-Policy"] = "default-src 'self'"
return response
  • 手动添加安全相关响应头
  • 推荐生产环境配置:
    • HSTS强制HTTPS
    • CSP内容安全策略
    • X-Content-Type-Options防MIME嗅探

4.生产环境建议

  1. 性能优化
    • 大文件使用FileResponse自动处理范围请求
    • 流式数据优先使用StreamingResponse
  2. 类型声明
    1
    2
    3
    @app.get("/logo.png", response_class=FileResponse)
    async def get_logo():
    return "static/logo.png"
  3. 错误处理
    1
    2
    3
    4
    from fastapi import HTTPException
    @app.get("/error-demo")
    async def error_demo():
    raise HTTPException(418, detail="我是茶壶")

测试命令示例:

1
curl -i http://localhost:8000/custom-response