FastAPI学习-8.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 元数据。

posted @ 2022-03-03 22:41  上海-悠悠  阅读(395)  评论(0编辑  收藏  举报