FASTAPI系列 09-POST请求BODY校验添加Field

FASTAPI系列 09-POST请求BODY校验添加Field

前言

使用 Pydantic 的 Field 在 Pydantic 模型内部声明校验和元数据。

一、Field 字段参数说明

关于 Field 字段参数说明

  • Field(None) 是可选字段,不传的时候值默认为None
  • Field(…) 是设置必填项字段
  • title 自定义标题,如果没有默认就是字段属性的值
  • description 定义字段描述内容

定义Book的Model

from pydantic import BaseModel, Field


class Book(BaseModel):
    book_name: str
    description: str = Field(None,
                             title="The description of the user",
                             max_length=100)
    price: float = Field(...,
                         gt=0,
                         description="The price of the book")


# 定义一个字典
book_dict = {
    "book_name": "python",
    "description": "The description of the user",
    "price": 100.1
}

二、从 pydantic 导入 Field

from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Book(BaseModel):
    book_name: str
    description: str = Field(None,
                             title="The description of the user",
                             max_length=100)
    price: float = Field(...,
                         gt=0,
                         description="The price of the book")


@app.post("/books/")
async def create_book(book: Book = Body(..., embed=True)):
    results = {"book": book}
    return results

注意,Field 是直接从 pydantic 导入的,而不是像其他的(Query,Path,Body 等)都从 fastapi 导入。


总结

你可以使用 Pydantic 的 Field 为模型属性声明额外的校验和元数据。你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。

  • 15
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值