FastAPI: 请求体嵌套模型(8)

可以将一个模型属性定义为有多子元素的类型。List来实现

1
2
3
4
5
6
7
8
9
10
11
12
class Book(BaseModel):
name: str = Field(..., min_length=2, max_length=10)
price: float
description: Optional[str] = None
tag: List[str] = None

app = FastAPI()

@app.post('/books/')
def root(book: Book = Body(..., embed=True),
query: Optional[str] = None):

return book, query

还可以在模型里嵌套模型,可以做到任意深度嵌套,来实现更复杂的结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Author(BaseModel):
name: str
address: Optional[str] = None


class Book(BaseModel):
name: str
price: float
description: Optional[str] = None
author: Author

app = FastAPI()

@app.post('/authors/{id}')
def root(*,
id: int = Path(..., gt=12),
book: Book):

return id, book

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!