FastAPI 教程翻译 - 用户指南 9 - 请求主体 - 字段

FastAPI 教程翻译 - 用户指南 9 - 请求主体 - 字段

FastAPI Tutorial - User Guide - Body - Fields

The same way you can declare additional validation and metadata in path operation function parameters with Query, Path and Body, you can declare validation and metadata inside of Pydantic models using Pydantic’s Field.

您可以使用 QueryPathBody路径操作函数参数中声明其他验证和元数据的方式相同,也可以使用 Pydantic 的 Field 在 Pydantic 模型中声明验证和元数据。

Import Field

导入Field

First, you have to import it:

首先,您必须导入它:

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = Field(None, title="The description of the item", max_length=300)
    price: float = Field(..., gt=0, description="The price must be greater than zero")
    tax: float = None


@app.put("/items/{item_id}")
async def update_item(*, item_id: int, item: Item = Body(..., embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

Warning

警告

Notice that Field is imported directly from pydantic, not from fastapi as are all the rest (Query, Path, Body, etc).

请注意,Field 是直接从 pydantic 导入的,而不是从 fastapi 导入的,其余都是(QueryPathBody 等)。

Declare model attributes

声明模型属性

You can then use Field with model attributes:

然后,您可以将 Field 与模型属性一起使用:

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = Field(None, title="The description of the item", max_length=300)
    price: float = Field(..., gt=0, description="The price must be greater than zero")
    tax: float = None


@app.put("/items/{item_id}")
async def update_item(*, item_id: int, item: Item = Body(..., embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

Field works the same way as Query, Path and Body, it has all the same parameters, etc.

Field 的工作方式与 QueryPathBody 相同,所有参数都相同,依次类推。

Technical Details

技术细节

Actually, Query, Path and others you’ll see next create objects of subclasses of a common Param class, which is itself a subclass of Pydantic’s FieldInfo class.

实际上,QueryPath 以及其他您将在接下来看到的将创建常见的 Param 类的子类的对象,该类本身是 Pydantic 的 FieldInfo 类的子类。

And Pydantic’s Field returns an instance of FieldInfo as well.

并且 Pydantic 的 Field 也返回 FieldInfo 的实例。

Body also returns objects of a subclass of FieldInfo directly. And there are others you will see later that are subclasses of the Body class.

Body 也直接返回 FieldInfo 的子类的对象。还有其他一些您稍后会看到的是 Body 类的子类。

Remember that when you import Query, Path, and others from fastapi, those are actually functions that return special classes.

请记住,当您从 fastapi 导入 QueryPath 和其他文件时,这些实际上是返回特殊类的函数。

Tip

提示

Notice how each model’s attribute with a type, default value and Field has the same structure as a path operation function’s parameter, with Field instead of Path, Query and Body.

注意,每个具有类型、默认值和 Field 的模型的属性如何与路径操作函数的参数具有相同的结构,而不是 PathQueryBody

JSON Schema extras

JSON 模式额外内容

In Field, Path, Query, Body and others you’ll see later, you can declare extra parameters apart from those described before.

在稍后将看到的 FieldPathQueryBody 以及其他内容中,您可以声明除先前描述的参数之外的其他参数。

Those parameters will be added as-is to the output JSON Schema.

这些参数将原样添加到输出 JSON 模式中。

If you know JSON Schema and want to add extra information apart from what we have discussed here, you can pass that as extra keyword arguments.

如果您了解 JSON 模式,并且希望添加除此处讨论的内容以外的其他信息,则可以将其作为额外的关键字参数传递。

Warning

警告

Have in mind that extra parameters passed won’t add any validation, only annotation, for documentation purposes.

请记住,出于文档目的,传递的额外参数不会添加任何验证,而只会添加注释。

For example, you can use that functionality to pass a JSON Schema example field to a body request JSON Schema:

例如,您可以使用该功能将 JSON模式示例 的字段传递给 JSON 模式的请求主体:

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int,
    item: Item = Body(
        ...,
        example={
            "name": "Foo",
            "description": "A very nice Item",
            "price": 35.4,
            "tax": 3.2,
        },
    )
):
    results = {"item_id": item_id, "item": item}
    return results

And it would look in the /docs like this:

/docs 中看起来像这样:

在这里插入图片描述

Recap

回顾

You can use Pydantic’s Field to declare extra validations and metadata for model attributes.

您可以使用 Pydantic 的 Field 为模型属性声明额外的验证和元数据。

You can also use the extra keyword arguments to pass additional JSON Schema metadata.

您还可以使用 extra 关键字参数来传递其他 JSON 模式元数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值