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 模型提供的极高灵活性,同时保持代码的简单、简短和优雅。