🌐 Add Chinese translation for `docs/zh/docs/tutorial/encoder.md` (#4969)

This commit is contained in:
Zssaer 2022-09-04 21:39:06 +08:00 committed by GitHub
parent 89839eb834
commit 0d43b6552b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,42 @@
# JSON 兼容编码器
在某些情况下您可能需要将数据类型如Pydantic模型转换为与JSON兼容的数据类型如`dict`、`list`等)。
比如,如果您需要将其存储在数据库中。
对于这种要求, **FastAPI**提供了`jsonable_encoder()`函数。
## 使用`jsonable_encoder`
让我们假设你有一个数据库名为`fake_db`它只能接收与JSON兼容的数据。
例如,它不接收`datetime`这类的对象因为这些对象与JSON不兼容。
因此,`datetime`对象必须将转换为包含<a href="https://en.wikipedia.org/wiki/ISO_8601" class="external-link" target="_blank">ISO格式化</a>的`str`类型对象。
同样这个数据库也不会接收Pydantic模型带有属性的对象而只接收`dict`。
对此你可以使用`jsonable_encoder`。
它接收一个对象比如Pydantic模型并会返回一个JSON兼容的版本
=== "Python 3.6 and above"
```Python hl_lines="5 22"
{!> ../../../docs_src/encoder/tutorial001.py!}
```
=== "Python 3.10 and above"
```Python hl_lines="4 21"
{!> ../../../docs_src/encoder/tutorial001_py310.py!}
```
在这个例子中它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。
调用它的结果后就可以使用Python标准编码中的<a href="https://docs.python.org/3/library/json.html#json.dumps" class="external-link" target="_blank">`json.dumps()`</a>
这个操作不会返回一个包含JSON格式作为字符串数据的庞大的`str`。它将返回一个Python标准数据结构例如`dict`其值和子值都与JSON兼容。
!!! note
`jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。

View File

@ -85,6 +85,7 @@ nav:
- tutorial/request-forms-and-files.md
- tutorial/handling-errors.md
- tutorial/path-operation-configuration.md
- tutorial/encoder.md
- tutorial/body-updates.md
- 依赖项:
- tutorial/dependencies/index.md