FastAPI教程 請(qǐng)求體 - 字段

2022-08-20 11:34 更新

與使用 Query、Path 和 Body 在路徑操作函數(shù)中聲明額外的校驗(yàn)和元數(shù)據(jù)的方式相同,你可以使用 Pydantic 的 Field 在 Pydantic 模型內(nèi)部聲明校驗(yàn)和元數(shù)據(jù)。

導(dǎo)入 Field

首先,你必須導(dǎo)入它:

from typing import Optional

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

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[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: Optional[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

注意,F(xiàn)ield 是直接從 pydantic 導(dǎo)入的,而不是像其他的(Query,Path,Body 等)都從 fastapi 導(dǎo)入。

聲明模型屬性

然后,你可以對(duì)模型屬性使用 Field:

from typing import Optional

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

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[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: Optional[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 的工作方式和 Query、Path 和 Body 相同,包括它們的參數(shù)等等也完全相同。

技術(shù)細(xì)節(jié)

實(shí)際上,Query、Path 和其他你將在之后看到的類,創(chuàng)建的是由一個(gè)共同的 Params 類派生的子類的對(duì)象,該共同類本身又是 Pydantic 的 FieldInfo 類的子類。

Pydantic 的 Field 也會(huì)返回一個(gè) FieldInfo 的實(shí)例。

Body 也直接返回 FieldInfo 的一個(gè)子類的對(duì)象。還有其他一些你之后會(huì)看到的類是 Body 類的子類。

請(qǐng)記住當(dāng)你從 fastapi 導(dǎo)入 Query、Path 等對(duì)象時(shí),他們實(shí)際上是返回特殊類的函數(shù)。

Tip

注意每個(gè)模型屬性如何使用類型、默認(rèn)值和 Field 在代碼結(jié)構(gòu)上和路徑操作函數(shù)的參數(shù)是相同的,區(qū)別是用 Field 替換Path、Query 和 Body。

添加額外信息

你可以在 Field、Query、Body 中聲明額外的信息。這些信息將包含在生成的 JSON Schema 中。

你將在文檔的后面部分學(xué)習(xí)聲明示例時(shí),了解到更多有關(guān)添加額外信息的知識(shí)。

總結(jié)

你可以使用 Pydantic 的 Field 為模型屬性聲明額外的校驗(yàn)和元數(shù)據(jù)。

你還可以使用額外的關(guān)鍵字參數(shù)來(lái)傳遞額外的 JSON Schema 元數(shù)據(jù)。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)