Skip to content

Commit

Permalink
Merge pull request #44 from hacker4257/main
Browse files Browse the repository at this point in the history
Translate docs/schema
  • Loading branch information
greyli authored Nov 26, 2024
2 parents 9ee0644 + ab2dbb4 commit 4653c9d
Showing 1 changed file with 70 additions and 112 deletions.
182 changes: 70 additions & 112 deletions docs_zh/schema.md
Original file line number Diff line number Diff line change
@@ -1,73 +1,56 @@
# Data Schema
# 数据模式

Read [this section](/usage/#use-appinput-to-validate-and-deserialize-request-data) and following
section first in the Basic Usage chapter for the basics of writing input and output schema.
请先阅读基础使用章节中[这一节](/usage/#use-appinput-to-validate-and-deserialize-request-data)及后续内容来了解编写输入输出模式的基础知识。

Basic concepts on data schema:
数据模式的基本概念:

- APIFlask's `apiflask.Schema` base class is directly imported from marshmallow with some minor changes,
see the [API documentation](https://marshmallow.readthedocs.io/en/stable/marshmallow.schema.html)
for the details.
- We recommend separating input and output schema. Since the output data is not
validated, you don't need to define validators on output fields.
- `apiflask.fields` includes all the fields provided by marshmallow, webargs, and
flask-marshmallow (while some aliases were removed).
- `apiflask.validators` includes all the validators in `marshmallow.validate`.
- For other functions/classes, just import them from marshmallow.
- Read [marshmallow's documentation](https://marshmallow.readthedocs.io/) when you have free time.
- APIFlask 的 `apiflask.Schema` 基类直接从 marshmallow 导入,带有一些细微改动,详见 [API 文档](https://marshmallow.readthedocs.io/en/stable/marshmallow.schema.html)
- 我们建议分开定义输入和输出模式。由于输出数据不需要验证,因此无需在输出字段上定义验证器。
- `apiflask.fields` 包含了 marshmallow、webargs 和 flask-marshmallow 提供的所有字段(某些别名已被移除)。
- `apiflask.validators` 包含 `marshmallow.validate` 中的所有验证器。
- 对于其他函数/类,直接从 marshmallow 导入即可。
- 建议在空闲时阅读[marshmallow](https://marshmallow.readthedocs.io/) 的文档 。

## 反序列化(load)和序列化(dump)

## Deserialization (load) and serialization (dump)
在 APIFlask(marshmallow)中,解析和验证输入请求数据的过程称为反序列化(我们从请求中 **load** 数据)。而格式化输出响应数据的过程称为序列化(我们将数据 **dump** 到响应中)。

In APIFlask (marshmallow), the process of parsing and validating the input request data
is called deserialization (we **load** the data from the request). And the process of
formatting the output response data is called serialization (we **dump** the data to
the response).
注意我们使用 "load" 和 "dump" 来表示这两个过程。创建模式时,我们使用 `load_default` 参数为输入模式中的字段设置默认值,使用 `dump_default` 参数为输出模式中的字段设置默认值。

Notice we use the "load" and "dump" to represent these two processes. When creating
the schema, we set the default value for the fields in the input schema with the `load_default`
parameter, and we use the `dump_default` parameter to set the default value for fields
in the output schema.
有四个装饰器用于在 load/dump 过程中注册回调方法:

There are four decorators to register callback methods in the load/dump processes:
- `pre_load`:注册在解析/验证请求数据之前调用的方法
- `post_load`:注册在解析/验证请求数据之后调用的方法
- `pre_dump`:注册在格式化视图函数返回值之前调用的方法
- `post_dump`:注册在格式化视图函数返回值之后调用的方法

- `pre_load`: to register a method to invoke before parsing/validating the request data
- `post_load`: to register a method to invoke after parsing/validating the request data
- `pre_dump`: to register a method to invoke before formatting the return value of the view function
- `post_dump`: to register a method to invoke after formatting the return value of the view function
还有两个装饰器用于注册验证方法:

And there are two decorators to register a validation method:

- `validates(field_name)`: to register a method to validate a specified field
- `validates_schema`: to register a method to validate the whole schema
- `validates(field_name)`:注册验证指定字段的方法
- `validates_schema`:注册验证整个模式的方法

!!! tip

When using the `validates_schema`, notice the `skip_on_field_errors` is set to `True` as default:
> If skip_on_field_errors=True, this validation method will be skipped whenever validation errors
> have been detected when validating fields.
使用 `validates_schema` 时,注意 `skip_on_field_errors` 默认设为 `True`:
> 如果 skip_on_field_errors=True,当验证字段时检测到验证错误时,这个验证方法将被跳过。

Import these decorators directly from marshmallow:
直接从 marshmallow 导入这些装饰器:

```python
from marshmallow import pre_load, post_dump, validates
```

See [this chapter](https://marshmallow.readthedocs.io/en/stable/extending.html) and the
[API documentation](https://marshmallow.readthedocs.io/en/stable/marshmallow.decorators.html)
of these decorators for the details.

详细用法请参阅[这一章节](https://marshmallow.readthedocs.io/en/stable/extending.html) 和这些装饰器的 [API 文档](https://marshmallow.readthedocs.io/en/stable/marshmallow.decorators.html)

## Data fields
## 数据字段

APIFlask's `apiflask.fields` module includes all the data fields from marshmallow, webargs, and
Flask-Marshmallow. We recommend importing them from the `apiflask.fields` module:
APIFlask 的 `apiflask.fields` 模块包含了来自 marshmallow、webargs 和 Flask-Marshmallow 的所有数据字段。我们建议从 `apiflask.fields` 模块导入它们:

```python
from apiflask.fields import String, Integer
```

Or you prefer to keep a reference:
或者你也可以这样引用:

```python
from apiflask import Schema, fields
Expand All @@ -77,9 +60,9 @@ class FooBar(Schema):
bar = fields.Integer()
```

!!! warning "Some field aliases were removed"
!!! warning "部分字段别名已被移除"

The following field aliases were removed:
以下字段别名已被移除:

- `Str`
- `Int`
Expand All @@ -88,7 +71,7 @@ class FooBar(Schema):
- `UrlFor`
- `AbsoluteUrlFor`

Instead, you will need to use:
请改用:

- `String`
- `Integer`
Expand All @@ -97,13 +80,12 @@ class FooBar(Schema):
- `URLFor`
- `AbsoluteURLFor`

See [apiflask#63](https://github.com/apiflask/apiflask/issues/63) and
[marshmallow#1828](https://github.com/marshmallow-code/marshmallow/issues/1828)for more details.

详见 [apiflask#63](https://github.com/apiflask/apiflask/issues/63) 和
[marshmallow#1828](https://github.com/marshmallow-code/marshmallow/issues/1828)。

### marshmallow fields
### marshmallow 字段

API documentation: <https://marshmallow.readthedocs.io/en/stable/marshmallow.fields.html>
API 文档:<https://marshmallow.readthedocs.io/en/stable/marshmallow.fields.html>

- `AwareDateTime`
- `Boolean`
Expand Down Expand Up @@ -135,39 +117,33 @@ API documentation: <https://marshmallow.readthedocs.io/en/stable/marshmallow.fie
- `URL`
- `UUID`

## Flask-Marshmallow 字段

## Flask-Marshmallow fields

API documentation: <https://flask-marshmallow.readthedocs.io/en/latest/#flask-marshmallow-fields>
API 文档:<https://flask-marshmallow.readthedocs.io/en/latest/#flask-marshmallow-fields>

- `AbsoluteURLFor`
- `Hyperlinks`
- `URLFor`

## webargs 字段

## webargs fields

API documentation: <https://webargs.readthedocs.io/en/latest/api.html#module-webargs.fields>
API 文档:<https://webargs.readthedocs.io/en/latest/api.html#module-webargs.fields>

- `DelimitedList`
- `DelimitedTuple`

## APIFlask 字段

## APIFlask fields

API documentation: <https://apiflask.com/api/fields/#apiflask.fields.File>
API 文档:<https://apiflask.com/api/fields/#apiflask.fields.File>

- `File`

!!! tip

If the existing fields don't fit your needs, you can also create
[custom fields](https://marshmallow.readthedocs.io/en/stable/custom_fields.html).
如果现有字段不能满足你的需求,你也可以创建[自定义字段](https://marshmallow.readthedocs.io/en/stable/custom_fields.html)。
## 数据验证器


## Data validators

APIFlask's `aipflask.validators` contains all the validator class provided by marshmallow:
APIFlask 的 `apiflask.validators` 包含了 marshmallow 提供的所有验证器类:

- `ContainsNoneOf`
- `ContainsOnly`
Expand All @@ -182,10 +158,9 @@ APIFlask's `aipflask.validators` contains all the validator class provided by ma
- `URL`
- `Validator`

See the [API documentation](https://marshmallow.readthedocs.io/en/stable/marshmallow.validate.html)
for the detailed usage.
详细用法请参阅 [API 文档](https://marshmallow.readthedocs.io/en/stable/marshmallow.validate.html)

When specifying validators for a field, you can pass a single validator to the `validate` parameter:
为字段指定验证器时,你可以向 `validate` 参数传递单个验证器:

```python
from apiflask import Schema
Expand All @@ -197,7 +172,7 @@ class PetIn(Schema):
category = String(required=True, validate=OneOf(['dog', 'cat']))
```

Or pass a list of validators:
或传递一个验证器列表:

```python
from apiflask import Schema
Expand All @@ -211,31 +186,27 @@ class PetIn(Schema):

!!! tip

If the existing validators don't fit your needs, you can also create
[custom validators](https://marshmallow.readthedocs.io/en/stable/quickstart.html#validation).

如果现有验证器不能满足你的需求,你也可以创建[自定义验证器](https://marshmallow.readthedocs.io/en/stable/quickstart.html#validation)。

## Schema name resolver
## 模式名称解析器

!!! warning "Version >= 0.9.0"

This feature was added in the [version 0.9.0](/changelog/#version-090).
此功能在 [0.9.0 版本](/changelog/#version-090)中添加。

The OpenAPI schema name of each schema is resolved based on a resolver function, here is
the default schema name resolver used in APIFlask:
每个模式的 OpenAPI 模式名称都基于解析器函数来解析,以下是 APIFlask 中使用的默认模式名称解析器:

```python
def schema_name_resolver(schema):
name = schema.__class__.__name__ # get schema class name
if name.endswith('Schema'): # remove the "Schema" suffix
name = schema.__class__.__name__ # 获取模式类名
if name.endswith('Schema'): # 移除 "Schema" 后缀
name = name[:-6] or name
if schema.partial: # add a "Update" suffix for partial schema
if schema.partial: # 为部分模式添加 "Update" 后缀
name += 'Update'
return name
```

You can provide a custom schema name resolver by setting the `APIFlask.schema_name_resolver`
attribute:
你可以通过设置 `APIFlask.schema_name_resolver` 属性来提供自定义的模式名称解析器:

```python hl_lines="14"
from apiflask import APIFlask
Expand All @@ -254,18 +225,15 @@ app = APIFlask(__name__)
app.schema_name_resolver = my_schema_name_resolver
```

The schema name resolver should accept the schema object as argument and return the name.
模式名称解析器应该接受模式对象作为参数并返回名称。


## Base response schema customization
## 基础响应模式自定义

!!! warning "Version >= 0.9.0"

This feature was added in the [version 0.9.0](/changelog/#version-090).
此功能在 [0.9.0 版本](/changelog/#version-090)中添加。

When you set up the output of a view function with the `output` decorator, you need to
return the object or dict that matches the schema you passed to the `output` decorator. Then,
APIFlask will serialize the return value to response body:
当你使用 `output` 装饰器设置视图函数的输出时,你需要返回与传递给 `output` 装饰器的模式相匹配的对象或字典。然后,APIFlask 会将返回值序列化到响应体中:

```python
{
Expand All @@ -275,9 +243,7 @@ APIFlask will serialize the return value to response body:
}
```

However, You may want to insert the output data into a data field and add some meta fields.
So that you can return a unified response for all endpoints. For example, make all the
responses to the following format:
然而,你可能希望将输出数据插入到一个 data 字段中,并添加一些元数据字段。这样你就可以为所有端点返回统一的响应。例如,让所有响应采用以下格式:

```python
{
Expand All @@ -291,8 +257,7 @@ responses to the following format:
}
```

To achieve this, you will need to set a base response schema, then pass it to the configuration variable
`BASE_RESPONSE_SCHEMA`:
要实现这一点,你需要设置一个基础响应模式,然后将其传递给配置变量 `BASE_RESPONSE_SCHEMA`

```python
from apiflask import APIFlask, Schema
Expand All @@ -301,21 +266,20 @@ from apiflask.fields import String, Integer, Field
app = APIFlask(__name__)

class BaseResponse(Schema):
data = Field() # the data key
data = Field() # data
message = String()
code = Integer()

app.config['BASE_RESPONSE_SCHEMA'] = BaseResponse
```

The default data key is "data", you can change it to match your data field name in your schema
via the configuration variable `BASE_RESPONSE_DATA_KEY`:
默认的 data 键是 "data",你可以通过配置变量 `BASE_RESPONSE_DATA_KEY` 将其更改为与你的模式中的数据字段名称相匹配:

```python
app.config['BASE_RESPONSE_DATA_KEY '] = 'data'
app.config['BASE_RESPONSE_DATA_KEY'] = 'data'
```

Now you can return a dict matches the base response schema in your view functions:
现在你可以在视图函数中返回与基础响应模式相匹配的字典:

```python
@app.get('/')
Expand All @@ -328,21 +292,17 @@ def say_hello():
}
```

Check out [the complete example application](https://github.com/apiflask/apiflask/tree/main/examples/base_response/app.py)
for more details, see [the examples page](/examples) for running the example application.

查看[完整示例应用](https://github.com/apiflask/apiflask/tree/main/examples/base_response/app.py) 了解更多详情,运行示例应用请参阅[示例页面](/examples)

## Use dataclass as data schema
## 使用 dataclass 作为数据模式

With [marshmalow-dataclass](https://github.com/lovasoa/marshmallow_dataclass), you can define
dataclasses and then convert them into marshmallow schemas.
借助 [marshmalow-dataclass](https://github.com/lovasoa/marshmallow_dataclass) ,你可以定义 dataclass 然后将其转换为 marshmallow 模式。

```bash
$ pip install marshmallow-dataclass
```

You can use the `dataclass` decorator from marshmallow-dataclass to create the data class, then call the
`.Schema` attribute to get the corresponding marshmallow schema:
你可以使用 marshmallow-dataclass 中的 `dataclass` 装饰器来创建数据类,然后调用 `.Schema` 属性获取相应的 marshmallow 模式:

```python
from dataclasses import field
Expand Down Expand Up @@ -383,8 +343,6 @@ def create_pet(pet: PetIn):
}
```

Check out [the complete example application](https://github.com/apiflask/apiflask/tree/main/examples/dataclass/app.py)
for more details, see [the examples page](/examples) for running the example application.
查看[完整示例应用](https://github.com/apiflask/apiflask/tree/main/examples/dataclass/app.py) 了解更多详情。运行示例应用请参阅[示例页面](/examples)

Read [mashmallow-dataclass's documentation](https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html)
and [dataclasses](https://docs.python.org/3/library/dataclasses.html) for more information.
阅读 [mashmallow-dataclass 的文档](https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html)[dataclasses](https://docs.python.org/3/library/dataclasses.html) 了解更多信息。

0 comments on commit 4653c9d

Please sign in to comment.