FastAPI 教程翻译 - 用户指南 8 - 请求主体 - 多个参数

FastAPI 教程翻译 - 用户指南 8 - 请求主体 - 多个参数

FastAPI Tutorial - User Guide - Body - Multiple Parameters

Now that we have seen how to use Path and Query, let’s see more advanced uses of request body declarations.

既然我们已经了解了如何使用 PathQuery,那么让我们来看一下请求主体声明的更高级用法。

Mix Path, Query and body parameters

混合使用 PathQuery 和请求主体参数

First, of course, you can mix Path, Query and request body parameter declarations freely and FastAPI will know what to do.

首先,当然,您可以自由地混合 PathQuery 和请求主体参数声明,并且 FastAPI 将知道该怎么做。

And you can also declare body parameters as optional, by setting the default to None:

您还可以通过将默认值设置为 None 来声明请求主体参数为可选:

from fastapi import FastAPI, Path
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 = Path(..., title="The ID of the item to get", ge=0, le=1000),
    q: str = None,
    item: Item = None,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    if item:
        results.update({"item": item})
    return results

Note

信息

Notice that, in this case, the item that would be taken from the body is optional. As it has a None default value.

请注意,在这种情况下,由于它具有 None 默认值,将从请求主体中获取的 item 是可选的。

Multiple body parameters

多个请求主体参数

In the previous example, the path operations would expect a JSON body with the attributes of an Item, like:

在上一个示例中,路径操作将期望具有 Item 属性的 JSON 主体,例如:

{
    "name": "Foo",
    "description": "The pretender",
    "price": 42.0,
    "tax": 3.2
}

But you can also declare multiple body parameters, e.g. item and user:

但是您也可以声明多个请求主体参数,例如 itemuser

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


class User(BaseModel):
    username: str
    full_name: str = None


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

In this case, FastAPI will notice that there are more than one body parameters in the function (two parameters that are Pydantic models).

在这种情况下,FastAPI 将注意到该函数中有多个请求主体参数(两个参数都是 Pydantic 模型)。

So, it will then use the parameter names as keys (field names) in the body, and expect a body like:

因此,它将使用参数名称作为主体中的键(字段名称),并期望这样的主体:

{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    }
}

Note

注意

Notice that even though the item was declared the same way as before, it is now expected to be inside of the body with a key item.

请注意,即使以与以前相同的方式声明了 item,但现在仍可以使用键 item 将其放置在请求主体内部。

FastAPI will do the automatic conversion from the request, so that the parameter item receives it’s specific content and the same for user.

FastAPI 将根据请求进行自动转换,以便参数 item 接收其特定内容,并且与 user 相同。

It will perform the validation of the compound data, and will document it like that for the OpenAPI schema and automatic docs.

它将执行复合数据的验证,并将像 OpenAPI 模式和自动文档一样对其进行记录。

Singular values in body

请求主体的奇异值

The same way there is a Query and Path to define extra data for query and path parameters, FastAPI provides an equivalent Body.

同样,使用 QueryPath 为查询和路径参数定义额外的数据,FastAPI 提供了等效的 Body

For example, extending the previous model, you could decide that you want to have another key importance in the same body, besides the item and user.

例如,扩展先前的模型,您可以决定除了 itemuser 之外,还希望在同一请求主体中具有另一个键 importance

If you declare it as is, because it is a singular value, FastAPI will assume that it is a query parameter.

如果按原样声明它,因为它是一个奇异值,FastAPI 将假定它是一个查询参数。

But you can instruct FastAPI to treat it as another body key using Body:

但是您可以使用 Body 指示 FastAPI 将其视为另一个请求主体的键。

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


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


class User(BaseModel):
    username: str
    full_name: str = None


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

In this case, FastAPI will expect a body like:

在这种情况下,FastAPI 将期望像这样的请求主体:

{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    },
    "importance": 5
}

Again, it will convert the data types, validate, document, etc.

同样,它将转换数据类型、验证、文档等。

Multiple body params and query

多个请求主体参数和查询

Of course, you can also declare additional query parameters whenever you need, additional to any body parameters.

当然,除了任何请求主体参数之外,您还可以在需要时声明其他查询参数。

As, by default, singular values are interpreted as query parameters, you don’t have to explicitly add a Query, you can just do:

由于默认情况下,奇异值被解释为查询参数,因此不必显示添加 Query,您可以执行以下操作:

q: str = None

as in:

如:

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


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


class User(BaseModel):
    username: str
    full_name: str = None


@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int,
    item: Item,
    user: User,
    importance: int = Body(..., gt=0),
    q: str = None
):
    results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
    if q:
        results.update({"q": q})
    return results

Info

信息

Body also has all the same extra validation and metadata parameters as Query,Path and others you will see later.

Body 还具有 QueryPath 和稍后将看到的其他相同的额外验证和元数据参数。

Embed a single body parameter

嵌入单个请求主体参数

Let’s say you only have a single item body parameter from a Pydantic model Item.

假设您只有一个来自 Pydantic 模型 Item 的请求主体参数 item

By default, FastAPI will then expect its body directly.

默认情况下,FastAPI 将直接生成其请求主体。

But if you want it to expect a JSON with a key item and inside of it the model contents, as it does when you declare extra body parameters, you can use the special Body parameter embed:

但是,如果您希望它生成带有键 item 的 JSON 并在其中包含模型内容,就像在声明额外的请求主体参数时所做的那样,则可以使用特殊的 Body 参数 embed

item: Item = Body(..., embed=True)

as in:

如:

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(..., embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

In this case FastAPI will expect a body like:

在这种情况下,FastAPI 将生成像这样的请求主体:

{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    }
}

instead of:

代替:

{
    "name": "Foo",
    "description": "The pretender",
    "price": 42.0,
    "tax": 3.2
}

Recap

回顾

You can add multiple body parameters to your path operation function, even though a request can only have a single body.

您可以将多个请求主体参数添加到路径操作函数中,即使请求只能包含一个请求主体。

But FastAPI will handle it, give you the correct data in your function, and validate and document the correct schema in the path operation.

但是 FastAPI 会处理它,在函数中为您提供正确的数据,并在路径操作的验证和文档中使用正确的模式。

You can also declare singular values to be received as part of the body.

您还可以声明将奇异值作为请求主体的一部分来接收。

And you can instruct FastAPI to embed the body in a key even when there is only a single parameter declared.

而且,即使仅声明了一个参数,您也可以指示 FastAPI 将请求主体嵌入键中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值