W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
與使用 Query、Path 和 Body 在路徑操作函數(shù)中聲明額外的校驗和元數(shù)據(jù)的方式相同,你可以使用 Pydantic 的 Field 在 Pydantic 模型內(nèi)部聲明校驗和元數(shù)據(jù)。
首先,你必須導(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)添加額外信息的知識。
你可以使用 Pydantic 的 Field 為模型屬性聲明額外的校驗和元數(shù)據(jù)。
你還可以使用額外的關(guān)鍵字參數(shù)來傳遞額外的 JSON Schema 元數(shù)據(jù)。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: