0%

FastAPI自学教程(16) - Cookie参数模型

1. 模型化声明Cookie参数

1
2
3
4
5
6
7
8
9
10
11
12
13
from typing import Annotated
from fastapi import Cookie, FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@app.get("/items/")
async def read_items(cookies: Annotated[Cookies, Cookie()]):
return cookies
  • 支持使用Pydantic模型批量管理多个Cookie参数
  • FastAPI 0.115.0+版本支持该特性,Query/Header参数也可用此方式
  • 自动提取请求头中的Cookie字段进行验证和转换

2. 多版本兼容写法

1
2
3
4
5
6
7
8
9
10
11
12
# Python 3.8+兼容写法
from typing import Union
from fastapi import Cookie
from pydantic import BaseModel

class Cookies(BaseModel):
session_id: str
tracker: Union[str, None] = None

@app.get("/items/")
async def read_items(cookies: Cookies = Cookie()):
return cookies
  • 推荐优先使用Annotated注解方式
  • 旧版本兼容写法需注意类型声明方式
  • 支持模型复用,适用于需要统一校验规则的场景

3. 禁止额外Cookie配置

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

session_id: str
theme: str = "light"

@app.get("/strict/")
async def strict_cookie(cookies: Annotated[StrictCookies, Cookie()]):
return cookies
  • 通过model_config = {"extra": "forbid"}限制未声明Cookie
  • 客户端发送未定义Cookie会返回422错误(如santa_tracker
  • 适用于需要严格安全管控的接口场景

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参数说明,但无法直接交互测试
  • 需通过curl或Postman发送Cookie:
    1
    curl -b "session_id=abc;tracker=123" http://localhost:8000/items/
  • 浏览器测试需手动设置Cookie(开发者工具→Application→Cookies)