fastapi/docs/zh/docs/tutorial/request-form-models.md

79 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 表单模型 { #form-models }
你可以在 FastAPI 中使用 **Pydantic 模型**声明**表单字段**
/// info | 信息
要使用表单,首先安装 [`python-multipart`](https://github.com/Kludex/python-multipart)。
确保你创建一个[虚拟环境](../virtual-environments.md),激活它,然后再安装,例如:
```console
$ pip install python-multipart
```
///
/// note | 注意
自 FastAPI 版本 `0.113.0` 起支持此功能。🤓
///
## 表单的 Pydantic 模型 { #pydantic-models-for-forms }
你只需声明一个 **Pydantic 模型**,其中包含你希望接收的**表单字段**,然后将参数声明为 `Form`
{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供你定义的 Pydantic 模型。
## 检查文档 { #check-the-docs }
你可以在文档 UI 中验证它,地址为 `/docs`
<div class="screenshot">
<img src="/img/tutorial/request-form-models/image01.png">
</div>
## 禁止额外的表单字段 { #forbid-extra-form-fields }
在某些特殊使用情况下(可能并不常见),你可能希望将表单字段**限制**为仅在 Pydantic 模型中声明过的字段,并**禁止**任何**额外**的字段。
/// note | 注意
自 FastAPI 版本 `0.114.0` 起支持此功能。🤓
///
你可以使用 Pydantic 的模型配置来 `forbid` 任何 `extra` 字段:
{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}
如果客户端尝试发送一些额外的数据,他们将收到**错误**响应。
例如,客户端尝试发送如下表单字段:
* `username`: `Rick`
* `password`: `Portal Gun`
* `extra`: `Mr. Poopybutthole`
他们将收到一条错误响应,表明字段 `extra` 不被允许:
```json
{
"detail": [
{
"type": "extra_forbidden",
"loc": ["body", "extra"],
"msg": "Extra inputs are not permitted",
"input": "Mr. Poopybutthole"
}
]
}
```
## 总结 { #summary }
你可以使用 Pydantic 模型在 FastAPI 中声明表单字段。😎