|
| 1 | ++++ |
| 2 | +date = '2025-08-11T10:00:00+08:00' |
| 3 | +draft = false |
| 4 | +title = 'Fastapi Cookie and Header Parameters' |
| 5 | ++++ |
| 6 | +这篇文章介绍 Fastapi 的 Cookie 和 Header 参数 |
| 7 | + |
| 8 | +### Cookie Parameters |
| 9 | +通过定义 `Query` 和 `Path` 参数一样定义 `Cookie` 参数 |
| 10 | +```Python |
| 11 | +from typing Annotated |
| 12 | +from fastapi import Cookie, FastAPI |
| 13 | + |
| 14 | +app = FastAPI() |
| 15 | + |
| 16 | +@app.get("/items/") |
| 17 | +async def read_items(ads_id: Annotated[str | None, Cookie()] = None): |
| 18 | + return {"ads_id": ads_id} |
| 19 | +``` |
| 20 | + |
| 21 | +#### Cookie Parameters Models |
| 22 | +如果有一组相关的 cookies, 可以使用 Pydantic model 来声明. |
| 23 | + |
| 24 | +这样可以在多个部分复用这个模型, 同时还能一次性为所有参数声明验证规则和元数据. |
| 25 | + |
| 26 | +下面使用 Pydantic 模型定义 Cookies, 然后将参数声明为 `Cookie` |
| 27 | +```Python |
| 28 | +from typing import Annotated |
| 29 | +from fastapi import FastAPI, Cookie |
| 30 | +from pydantic import BaseModel |
| 31 | + |
| 32 | +app = FastAPI() |
| 33 | + |
| 34 | +class Cookie(BaseModel): |
| 35 | + session_id: str |
| 36 | + fatebook_tracker: str | None = None |
| 37 | + googall_tracker: str | None = None |
| 38 | + |
| 39 | +@app.get("/items/") |
| 40 | +async def read_items(cookies: Annotated[Cookies, Cookie()]): |
| 41 | + return cookies |
| 42 | +``` |
| 43 | + |
| 44 | +#### Forbid Extra Cookies 禁止额外的Cookie |
| 45 | +在某些场景下(虽然并不常见), 可能希望限制 API 只能接收特定的 Cookie. |
| 46 | +这样, API 就可以"自己"管理 Cookie 同意策略了. |
| 47 | +```Python |
| 48 | +from typing import Annotated |
| 49 | +from fastapi import FastAPI, Cookie |
| 50 | +from pydantic import BaseModel |
| 51 | + |
| 52 | +app = FastAPI() |
| 53 | + |
| 54 | +class Cookies(BaseModel): |
| 55 | + model_config = {"extra": "forbid"} # forbid extra cookies |
| 56 | + |
| 57 | + session_id: str |
| 58 | + fatebook_tracker: str | None = None |
| 59 | + googall_tracker: str | None = None |
| 60 | + |
| 61 | +@app.get("/items/") |
| 62 | +async def read_items(cookies: Annotated[Cookies, Cookie()]): |
| 63 | + return cookies |
| 64 | +``` |
| 65 | +这样, 如果客户端发送额外的 cookies, 则会收到一个错误响应. 例如, 客户端发送了 `santa_tracker` 这个额外 Cookie |
| 66 | +```Python |
| 67 | +santa_tracker = good-list-please |
| 68 | +``` |
| 69 | +将会收到如下错误响应 |
| 70 | +```JSON |
| 71 | +{ |
| 72 | + "detail": [ |
| 73 | + { |
| 74 | + "type": "extra_forbidden", |
| 75 | + "loc": ["cookie", "santa_tracker"], |
| 76 | + "msg": "Extra inputs are not permitted", |
| 77 | + "input": "good-list-please", |
| 78 | + } |
| 79 | + ] |
| 80 | +} |
| 81 | +``` |
| 82 | + |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | +### Header Parameters |
| 87 | +同样的, 通过定义 `Query` 和 `Path` 参数一样定义 `Header` 参数 |
| 88 | +```Python |
| 89 | +from typing import Annotated |
| 90 | +from fastapi import FastAPI, Header |
| 91 | + |
| 92 | +app = FastAPI() |
| 93 | + |
| 94 | +@app.get("/items/") |
| 95 | +async def read_items(user_agent: Annotated[str | None, Header()] = None): |
| 96 | + return {"User-Agent": user_agent} |
| 97 | +``` |
| 98 | + |
| 99 | + |
| 100 | +#### Automatic conversoin 自动转换 |
| 101 | +`Header` 拥有一些在 `Path`, `Query` 和 `Cookie` 上的额外功能 |
| 102 | + |
| 103 | +大多数标准的 header 都通过一个连字符(hyphen character), 也称为减号(minus symbol)分开, |
| 104 | +但是变量 `user-agent` 这样在 Python 中是不合法的. 所以, 默认情况下 `Header` 会将参数名中的 hypen(-) 使用下划线 undersocre(\_) 替换. |
| 105 | + |
| 106 | +同样的, HTTP headers 是不区分大小写的, 所以可以使用标准的 Python 风格 (snake\_case). 因此可以使用 `user_agent` 在 Python 代码中, 而不需要首字母大写成 `User_Agent`. |
| 107 | + |
| 108 | +如果想要禁止这种自动转换, 需要将 `Header` 的参数 `convert_undersocres` 设置为 `False` |
| 109 | + |
| 110 | +```Python |
| 111 | +from typing import Typing |
| 112 | +from fastapi import FastAPI, Header |
| 113 | + |
| 114 | +app = FastAPI() |
| 115 | + |
| 116 | +@app.get("/items/") |
| 117 | +async def read_items( |
| 118 | + strange_header: Annotated[str | None, Header(convert_undersocres=False)] = None |
| 119 | +): |
| 120 | + return {"strange_header": strange_header} |
| 121 | +``` |
| 122 | + |
| 123 | +#### Duplicate headers 重复请求头 |
| 124 | +一个请求中可能会收到重复的 headers, 也就是同一个 header 有多个值. |
| 125 | + |
| 126 | +可以在类型声明中使用 `list` 来处理这种情况, 这样会得到一个 Python 列表. |
| 127 | + |
| 128 | +例如要声明一个可能多次出现的 `X-Token` 头部, 可以这样写: |
| 129 | +```Python |
| 130 | +from typing import Annotated |
| 131 | +from fastapi import FastAPI, Header |
| 132 | + |
| 133 | +app = FastAPI() |
| 134 | + |
| 135 | +@app.get("/items/") |
| 136 | +async def read_items(x_token: Annotated[list[str] | None, Header()] = None): |
| 137 | + return {"X-Token values": x_token} |
| 138 | +``` |
| 139 | + |
| 140 | +如果向该接口发送两个这样的 HTTP headers |
| 141 | +``` |
| 142 | +X-Token: foo |
| 143 | +X-Token: bar |
| 144 | +``` |
| 145 | + |
| 146 | +返回类似这样 |
| 147 | +```Python |
| 148 | +{ |
| 149 | + "X-Token values": [ |
| 150 | + "bar", |
| 151 | + "foo" |
| 152 | + ] |
| 153 | +} |
| 154 | +``` |
| 155 | + |
| 156 | + |
| 157 | +#### Header parameters models 请求头参数模型 |
| 158 | +同样可以使用 Pydantic model 定义 Header Parameters, 这样可以在多个地方复用模型, 还能一次性为所有参数声明规则和元数据 |
| 159 | +```Python |
| 160 | +from typing import Annotated |
| 161 | +from fastapi import FastAPI, Header |
| 162 | +from pydantic import BaseModel |
| 163 | + |
| 164 | +app = FastAPI() |
| 165 | + |
| 166 | +class CommonHeaders(BaseModel): |
| 167 | + host: str |
| 168 | + save_data: str |
| 169 | + if_modified_since: str | None = None |
| 170 | + traceparent: str | None = None |
| 171 | + x_tag: list[str] = [] |
| 172 | + |
| 173 | +@app.get("/items") |
| 174 | +async def read_items(headers: Annotated[CommonHeaders, Header()]): |
| 175 | + return headers |
| 176 | +``` |
| 177 | + |
| 178 | +#### Forbid extra headers 禁止额外请求头 |
| 179 | +同样也可以禁止额外的 headers |
| 180 | +```Python |
| 181 | +class CommonHeaders(BaseModel): |
| 182 | + model_config = {"extra": "forbid"} # 禁止额外字段 |
| 183 | + ... |
| 184 | +``` |
| 185 | + |
| 186 | +如果客户端尝试发送额外的 Header,将会收到错误响应. 例如, 客户端发送了 `tool` 这个额外 Header |
| 187 | +``` |
| 188 | +tool: plumbus |
| 189 | +``` |
| 190 | + |
| 191 | +将会收到如下错误响应 |
| 192 | +```json |
| 193 | +{ |
| 194 | + "detail": [ |
| 195 | + { |
| 196 | + "type": "extra_forbidden", |
| 197 | + "loc": ["header", "tool"], |
| 198 | + "msg": "Extra inputs are not permitted", |
| 199 | + "input": "plumbus" |
| 200 | + } |
| 201 | + ] |
| 202 | +} |
| 203 | +``` |
| 204 | + |
| 205 | +#### Disable convert undersocres |
| 206 | +同样可以禁用自动下换线转换 |
| 207 | + |
| 208 | +与普通的 Header 参数一样, 如果参数名中包含下划线 undersocre (\_), FastAPI 会自动将其转换为连字符 hypens (-) |
| 209 | +```Python |
| 210 | +async def read_items( |
| 211 | + headers: Annotated[CommonHeaders, Header(convert_underscores=False)], |
| 212 | +): |
| 213 | + ... |
| 214 | +``` |
| 215 | + |
| 216 | +> 在将 `convert_underscores` 设置为 False 前, 注意有些 HTTP 代理和服务器不允许带下划线的头部字段 |
0 commit comments