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

成都創(chuàng)新互聯(lián)公司是一家專注于成都做網站、成都網站建設、成都外貿網站建設與策劃設計,饒河網站建設哪家好?成都創(chuàng)新互聯(lián)公司做網站,專注于網站建設10余年,網設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:饒河等地區(qū)。饒河做網站價格咨詢:028-86922220
導入 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
Warning
注意,F(xiàn)ield 是直接從 pydantic 導入的,而不是像其他的(Query,Path,Body 等)都從 fastapi 導入。
聲明模型屬性
然后,你可以對模型屬性使用 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ù)等等也完全相同。
技術細節(jié)
實際上,Query、Path 和其他你將在之后看到的類,創(chuàng)建的是由一個共同的 Params 類派生的子類的對象,該共同類本身又是 Pydantic 的 FieldInfo 類的子類。
Pydantic 的 Field 也會返回一個 FieldInfo 的實例。
Body 也直接返回 FieldInfo 的一個子類的對象。還有其他一些你之后會看到的類是 Body 類的子類。
請記住當你從 fastapi 導入 Query、Path 等對象時,他們實際上是返回特殊類的函數(shù)。
Tip
注意每個模型屬性如何使用類型、默認值和 Field 在代碼結構上和路徑操作函數(shù)的參數(shù)是相同的,區(qū)別是用 Field 替換Path、Query 和 Body。
添加額外信息
你可以在 Field、Query、Body 中聲明額外的信息。這些信息將包含在生成的 JSON Schema 中。
你將在文檔的后面部分學習聲明示例時,了解到更多有關添加額外信息的知識。
總結
你可以使用 Pydantic 的 Field 為模型屬性聲明額外的校驗和元數(shù)據。
你還可以使用額外的關鍵字參數(shù)來傳遞額外的 JSON Schema 元數(shù)據。
分享題目:創(chuàng)新互聯(lián)FastAPI教程:FastAPI教程請求體-字段
路徑分享:http://m.5511xx.com/article/coededp.html


咨詢
建站咨詢
