FastAPI进阶指南:快速掌握请求与响应核心机制
一、FastAPI请求处理机制解析
FastAPI的请求处理基于ASGI标准,通过依赖注入系统实现参数自动解析。其核心优势在于:
- 类型注解驱动:利用Python类型注解自动生成OpenAPI文档
- 异步支持:原生支持async/await语法
- 数据验证:集成Pydantic实现请求数据校验
1.1 路径参数处理
路径参数通过花括号{}定义,支持类型转换和正则验证:
from fastapi import FastAPI, Pathapp = FastAPI()@app.get("/items/{item_id}")async def read_item(item_id: int = Path(..., ge=1, description="物品ID必须大于等于1")):return {"item_id": item_id}
关键参数说明:
...表示必填参数ge/le/gt/lt实现数值范围验证regex参数支持正则表达式验证
1.2 查询参数处理
查询参数通过函数参数定义,支持默认值和可选参数:
from typing import Optional@app.get("/items/")async def read_items(skip: int = 0,limit: int = 100,sort: Optional[str] = None):return {"skip": skip, "limit": limit, "sort": sort}
进阶技巧:
- 使用
Query类实现更复杂的验证
```python
from fastapi import Query
@app.get(“/search/“)
async def search_items(
q: str = Query(…, min_length=3, max_length=50)
):
return {“search_term”: q}
## 二、请求体处理深度实践FastAPI通过Pydantic模型实现请求体验证,支持JSON、表单数据和文件上传。### 2.1 JSON请求体```pythonfrom pydantic import BaseModelclass Item(BaseModel):name: strdescription: Optional[str] = Noneprice: floattax: Optional[float] = None@app.post("/items/")async def create_item(item: Item):item_dict = item.dict()if item.tax:price_with_tax = item.price + item.taxitem_dict.update({"price_with_tax": price_with_tax})return item_dict
2.2 表单数据处理
from fastapi import Form@app.post("/login/")async def login(username: str = Form(...),password: str = Form(...)):return {"username": username}
2.3 文件上传
from fastapi import UploadFile, File@app.post("/upload/")async def upload_file(file: UploadFile = File(...)):contents = await file.read()return {"filename": file.filename,"content_type": file.content_type,"size": len(contents)}
三、响应处理高级技巧
FastAPI提供多种响应方式,支持自定义状态码、响应头和媒体类型。
3.1 响应模型控制
from fastapi import HTTPException@app.get("/items/{item_id}")async def read_item(item_id: int):if item_id == 42:raise HTTPException(status_code=404,detail="Item not found")return {"item_id": item_id}
3.2 自定义响应
from fastapi.responses import JSONResponse, StreamingResponse@app.get("/stream/")async def stream_data():def generate():for i in range(10):yield f"data chunk {i}\n"return StreamingResponse(generate(), media_type="text/plain")
3.3 响应头管理
from fastapi import Response@app.get("/headers/")async def get_headers(response: Response):response.headers["X-Custom-Header"] = "FastAPI"return {"message": "Headers set"}
四、状态码管理最佳实践
FastAPI支持标准HTTP状态码和自定义状态码:
4.1 常用状态码示例
from fastapi import status@app.post("/items/", status_code=status.HTTP_201_CREATED)async def create_item(item: Item):return item
4.2 自定义状态码
@app.put("/items/{item_id}", status_code=202) # 202 Acceptedasync def update_item(item_id: int, item: Item):return {"item_id": item_id, "status": "updated"}
五、进阶应用场景
5.1 多部分请求处理
from fastapi import Request@app.post("/multipart/")async def handle_multipart(request: Request):form_data = await request.form()return {"username": form_data["username"],"avatar": form_data["avatar"].filename}
5.2 请求上下文管理
from fastapi import Request@app.get("/context/")async def get_context(request: Request):client_host = request.client.hostmethod = request.methodreturn {"client": client_host, "method": method}
六、性能优化建议
- 异步处理:对I/O密集型操作使用async/await
- 数据验证:合理使用Pydantic的
@validator装饰器 - 响应压缩:启用中间件进行响应压缩
```python
from fastapi.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=1000)
## 七、调试与测试技巧1. **请求日志**:配置UVICORN日志级别```bashuvicorn main:app --log-level debug
- 测试客户端:使用TestClient编写单元测试
```python
from fastapi.testclient import TestClient
client = TestClient(app)
def test_read_item():
response = client.get(“/items/5?q=test”)
assert response.status_code == 200
assert response.json() == {“item_id”: 5}
## 八、安全实践1. **CSRF保护**:启用中间件```pythonfrom fastapi.middleware.csrf import CSRFMiddlewareapp.add_middleware(CSRFMiddleware, secret_key="YOUR-SECRET-KEY")
- 速率限制:使用慢API中间件
```python
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@app.get(“/limited/“)
@limiter.limit(“5/minute”)
async def limited_endpoint():
return {“message”: “This is a rate-limited endpoint”}
```
通过系统掌握这些核心机制,开发者可以高效构建健壮的FastAPI应用。建议结合实际项目需求,逐步实践这些技术点,并通过阅读FastAPI官方文档深入理解底层原理。