1. 程式人生 > 其它 >FastAPI學習-7.POST請求body中新增Field

FastAPI學習-7.POST請求body中新增Field

前言

與使用 Query、Path 和 Body 在路徑操作函式中宣告額外的校驗和元資料的方式相同,你可以使用 Pydantic 的 Field 在 Pydantic 模型內部宣告校驗和元資料。

Field 欄位引數說明

關於 Field 欄位引數說明

  • Field(None) 是可選欄位,不傳的時候值預設為None
  • Field(...) 是設定必填項欄位
  • title 自定義標題,如果沒有預設就是欄位屬性的值
  • description 定義欄位描述內容
from pydantic import BaseModel, Field


class Item(BaseModel):
    name: str
    description: str = Field(None,
                             title="The description of the item",
                             max_length=10)
    price: float = Field(...,
                         gt=0,
                         description="The price must be greater than zero")
    tax: float = None


a = Item(name="yo yo",
         price=22.0,
         tax=0.9)
print(a.dict())  # {'name': 'yo yo', 'description': None, 'price': 22.0, 'tax': 0.9}

匯入 Field

是從 pydantic 匯入 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 是直接從 pydantic 匯入的,而不是像其他的(Query,Path,Body 等)都從 fastapi 匯入。

總結
你可以使用 Pydantic 的 Field 為模型屬性宣告額外的校驗和元資料。
你還可以使用額外的關鍵字引數來傳遞額外的 JSON Schema 元資料。