FASTAPI 11-请求BODY的嵌套模型创建

FASTAPI 11-请求BODY的嵌套模型创建



前言

使用 FastAPI,你可以定义、校验、记录文档并使用任意深度嵌套的模型,使用Pydantic创建模型


一、声明属性子类型

将一个属性定义为拥有子元素的类型,首先,从Python的标准库 typing 模块中导入 List,使用方括号 [ 和 ] 将子类型作为「类型参数」传入,这完全是用于类型声明的标准 Python 语法。

from typing import Optional, List
from fastapi import Body, FastAPI, APIRouter
from pydantic import BaseModel, Field
router = APIRouter()

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")
    book_classification: List[str] = []


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

还可以给book添加tag属性,添加标签,但是标签不应该重复,我们在模型中,使用Set类型,代码更新如下:

from typing import Optional, List, Set
from fastapi import Body, FastAPI, APIRouter
from pydantic import BaseModel, Field
router = APIRouter()

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")
    book_classification: List[str] = []
    tags: Set[str] = []


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

即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。而且,每当你输出该数据时,即使源数据有重复,它们也将作为一组唯一项输出。并且还会被相应地标注 / 记录文档。

二、嵌套模型

Pydantic 模型的每个属性都具有类型。但是这个类型本身可以是另一个 Pydantic 模型。因此,你可以声明拥有特定属性名称、类型和校验的深度嵌套的 JSON 对象。上述这些都可以任意的嵌套。

1.定义子模型

定义一个出版社的模型, 将子模型用作Book模型的public属性的类型


class Public(BaseModel):
    public_name:str
    public_address: str


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_classification: List[str] = []
    tags: Set[str] = []
    public: Union[Public, None]

则该接口期望的请求Body为:

{
	"book_name":"Python",
	"description":"This is a book",
	"price":42.0,
	"book_classification":[
		"小说",
		"杂志"
		],
	"tags":[
		"python",
		"java"
		],
	"public":{
		"public_name":"工业出版社",
		"public_address":"中国"
		}
}

仅仅进行这样的声明,你将通过 FastAPI 获得:对被嵌入的模型也适用的编辑器支持(自动补全等)
数据转换,数据校验,自动生成文档

2.深度嵌套模型

可以定义任意深度的嵌套模型:

class Public(BaseModel):
    public_name:str
    public_address: str


class Images(BaseModel):
    image_name: str
    image_url: str


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_classification: List[str] = []
    tags: Set[str] = []
    public: Union[Public, None]
    images: Images	

总结

使用 FastAPI 你可以拥有 Pydantic 模型提供的极高灵活性,同时保持代码的简单、简短和优雅。

更多内容,请+V lzq599220 关注公众号,持续更新,并赠送80G免费测试python开发课程

在这里插入图片描述

更多课程,请关注公众号

在这里插入图片描述

  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值