0%

FastAPI自学教程(14)- Cookie参数处理

1. 基础声明方式

1
2
3
4
5
6
7
8
from fastapi import Cookie, FastAPI
from typing import Annotated

app = FastAPI()

@app.get("/items/")
async def read_items(ads_id: Annotated[str | None, Cookie()] = None):
return {"ads_id": ads_id}
  • 必须使用 Cookie() 声明参数,否则会被识别为查询参数
  • 参数名需与客户端cookie的key完全一致才能正确接收
  • 支持类型注解与默认值设置,未传值时默认为None

2. 模型化处理

1
2
3
4
5
6
7
8
9
10
from pydantic import BaseModel
from fastapi import Cookie, Annotated

class CookieModel(BaseModel):
session_id: str
tracker: str | None = None

@app.get("/model/")
async def model_cookie(cookie: Annotated[CookieModel, Cookie()]):
return cookie
  • 支持使用Pydantic模型批量管理多个Cookie参数
  • 自动提取请求头中的对应字段进行验证和转换
  • 模型可复用,适用于需要统一校验规则的场景

3. 禁止额外Cookie

1
2
3
4
5
6
7
8
9
class StrictCookie(BaseModel):
model_config = {"extra": "forbid"}

user_token: str
theme: str = "light"

@app.get("/strict/")
async def strict_cookie(cookie: Annotated[StrictCookie, Cookie()]):
return cookie
  • 通过模型配置禁止客户端发送未声明的Cookie
  • 违规时会返回422错误(如客户端发送未定义的lang参数)
  • 适用于需要严格管控Cookie参数的安全场景

4. 文档交互说明

1
2
3
4
5
6
# Swagger UI会显示Cookie参数文档
@app.get("/docs-demo/")
async def docs_demo(
debug_mode: Annotated[bool, Cookie()] = False
):
return {"debug": debug_mode}
  • 文档界面会展示Cookie参数的字段说明
  • 浏览器测试时需手动设置Cookie(开发者工具→Application→Cookies)
  • JavaScript无法直接操作受HTTP Only保护的Cookie

5. 高级配置技巧

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

@app.get("/set-cookie/")
async def set_cookie():
content = {"message": "Cookie set"}
response = JSONResponse(content=content)
response.set_cookie(
key="user_session",
value="abc123",
max_age=3600,
httponly=True,
samesite="strict"
)
return response
  • 通过Response对象设置安全Cookie(需导入JSONResponse
  • 支持max_agedomainsecure等高级参数配置
  • 建议敏感Cookie启用httponlysamesite防护