File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 查询参数模型
2+
3+ 如果你有一组具有相关性的** 查询参数** ,你可以创建一个 ** Pydantic 模型** 来声明它们。
4+
5+ 这将允许你在** 多个地方** 去** 复用模型** ,并且一次性为所有参数声明验证和元数据。😎
6+
7+ /// note
8+
9+ FastAPI 从 ` 0.115.0 ` 版本开始支持这个特性。🤓
10+
11+ ///
12+
13+ ## 使用 Pydantic 模型的查询参数
14+
15+ 在一个 ** Pydantic模型** 中声明你需要的** 查询参数** ,然后将参数声明为 ` Query ` :
16+
17+ {* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[ 9:13,17] * }
18+
19+ ** FastAPI** 将会从请求的** 查询参数** 中** 提取** 出** 每个字段** 的数据,并将其提供给你定义的 Pydantic 模型。
20+
21+ ## 查看文档
22+
23+ 你可以在 ` /docs ` 页面的 UI 中查看查询参数:
24+
25+ <div class =" screenshot " >
26+ <img src =" /img/tutorial/query-param-models/image01.png " >
27+ </div >
28+
29+ ## 禁止额外的查询参数
30+
31+ 在一些特殊的使用场景中(可能不是很常见),你可能希望** 限制** 你要接收的查询参数。
32+
33+ 你可以使用 Pydantic 的模型配置来 ` forbid ` (意为禁止 —— 译者注)任何 ` extra ` (意为额外的 —— 译者注)字段:
34+
35+ {* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[ 10] * }
36+
37+ 如果客户端尝试在** 查询参数** 中发送一些** 额外的** 数据,他们将会收到一个** 错误** 响应。
38+
39+ 例如,如果客户端尝试发送一个值为 ` plumbus ` 的 ` tool ` 查询参数,如:
40+
41+ ``` http
42+ https://example.com/items/?limit=10&tool=plumbus
43+ ```
44+
45+ 他们将收到一个** 错误** 响应,告诉他们查询参数 ` tool ` 是不允许的:
46+
47+ ``` json
48+ {
49+ "detail" : [
50+ {
51+ "type" : " extra_forbidden" ,
52+ "loc" : [" query" , " tool" ],
53+ "msg" : " Extra inputs are not permitted" ,
54+ "input" : " plumbus"
55+ }
56+ ]
57+ }
58+ ```
59+
60+ ## 总结
61+
62+ 你可以使用 ** Pydantic 模型** 在 ** FastAPI** 中声明** 查询参数** 。😎
63+
64+ /// tip
65+
66+ 剧透警告:你也可以使用 Pydantic 模型来声明 cookie 和 headers,但你将在本教程的后面部分阅读到这部分内容。🤫
67+
68+ ///
You can’t perform that action at this time.
0 commit comments