FastAPI教程 請求體 - 字段

2022-08-20 11:34 更新

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

聲明模型屬性

然后,你可以對模型屬性使用 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ù)細節(jié)

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

Pydantic 的 Field 也會返回一個 FieldInfo 的實例。

Body 也直接返回 FieldInfo 的一個子類的對象。還有其他一些你之后會看到的類是 Body 類的子類。

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

Tip

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

添加額外信息

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

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

總結(jié)

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

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


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號