From 0d43b6552b30bb81d2f62536cc4faa5aa4251e64 Mon Sep 17 00:00:00 2001 From: Zssaer <45691504+Zssaer@users.noreply.github.com> Date: Sun, 4 Sep 2022 21:39:06 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translation=20fo?= =?UTF-8?q?r=20`docs/zh/docs/tutorial/encoder.md`=20(#4969)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/encoder.md | 42 ++++++++++++++++++++++++++++++++ docs/zh/mkdocs.yml | 1 + 2 files changed, 43 insertions(+) create mode 100644 docs/zh/docs/tutorial/encoder.md diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md new file mode 100644 index 000000000..cb813940c --- /dev/null +++ b/docs/zh/docs/tutorial/encoder.md @@ -0,0 +1,42 @@ +# JSON 兼容编码器 + +在某些情况下,您可能需要将数据类型(如Pydantic模型)转换为与JSON兼容的数据类型(如`dict`、`list`等)。 + +比如,如果您需要将其存储在数据库中。 + +对于这种要求, **FastAPI**提供了`jsonable_encoder()`函数。 + +## 使用`jsonable_encoder` + +让我们假设你有一个数据库名为`fake_db`,它只能接收与JSON兼容的数据。 + +例如,它不接收`datetime`这类的对象,因为这些对象与JSON不兼容。 + +因此,`datetime`对象必须将转换为包含ISO格式化的`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标准编码中的`json.dumps()`。 + +这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。 + +!!! note + `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml index b60a0b7a1..ac8679dc0 100644 --- a/docs/zh/mkdocs.yml +++ b/docs/zh/mkdocs.yml @@ -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