Skip to content

Commit

Permalink
🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params-…
Browse files Browse the repository at this point in the history
…str-validations.md` (#5255)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
hjlarry and pre-commit-ci[bot] committed Oct 31, 2022
1 parent 53127ef commit db4452d
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions docs/zh/docs/tutorial/query-params-str-validations.md
Expand Up @@ -104,7 +104,7 @@ q: str
代替:

```Python
q: str = None
q: Union[str, None] = None
```

但是现在我们正在用 `Query` 声明它,例如:
Expand All @@ -113,17 +113,51 @@ q: str = None
q: Union[str, None] = Query(default=None, min_length=3)
```

因此,当你在使用 `Query` 且需要声明一个值是必需的时,可以将 `...` 用作第一个参数值
因此,当你在使用 `Query` 且需要声明一个值是必需的时,只需不声明默认参数

```Python hl_lines="7"
{!../../../docs_src/query_params_str_validations/tutorial006.py!}
```

### 使用省略号(`...`)声明必需参数

有另一种方法可以显式的声明一个值是必需的,即将默认参数的默认值设为 `...`

```Python hl_lines="7"
{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
```

!!! info
如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">Python 的一部分并且被称为「省略号」</a>。
Pydantic 和 FastAPI 使用它来显式的声明需要一个值。

这将使 **FastAPI** 知道此查询参数是必需的。

### 使用`None`声明必需参数

你可以声明一个参数可以接收`None`值,但它仍然是必需的。这将强制客户端发送一个值,即使该值是`None`

为此,你可以声明`None`是一个有效的类型,并仍然使用`default=...`

```Python hl_lines="9"
{!../../../docs_src/query_params_str_validations/tutorial006c.py!}
```

!!! tip
Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional``Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关<a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">必需可选字段</a>的更多信息。

### 使用Pydantic中的`Required`代替省略号(`...`)

如果你觉得使用 `...` 不舒服,你也可以从 Pydantic 导入并使用 `Required`

```Python hl_lines="2 8"
{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
```

!!! tip
请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...``Required`


## 查询参数列表 / 多个值

当你使用 `Query` 显式地定义查询参数时,你还可以声明它去接收一组值,或换句话来说,接收多个值。
Expand Down

0 comments on commit db4452d

Please sign in to comment.