您的位置:首页 > 其它

FastAPI(22)- Pydantic Model 结合 Union、List 的使用场景

2021-09-25 10:09 330 查看

前言

有多个模型,且请求/响应需要声明多个模型的时候,可以根据不同使用场景结合 typing 库里面的 Union、List 来达到目的

 

Union

作用

联合类型,详细教程

使用 Union 时,建议首先包含具体的类型,然后是不太具体的类型

 

实际代码

#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/9/22 8:28 上午
# file: 19_extra models.py
"""

import uvicorn
from fastapi import FastAPI
from typing import Optional, Union, List, Dict
from pydantic import BaseModel, EmailStr

app = FastAPI()

class BaseItem(BaseModel):
description: str
type: str

class CarItem(BaseItem):
# 给了个默认值
type = "car"

class PlaneItem(BaseItem):
type = "plane"
size: int

items = {
"item1": {"description": "All my friends drive a low rider", "type": "car"},
"item2": {
"description": "Music is my aeroplane, it's my aeroplane",
"type": "plane",
"size": 5,
},
}

@app.get("/items/{item_id}", response_model=Union[PlaneItem, CarItem])
async def read_item(item_id: str):
  # item_id 作为键去 items 中找到对应的值 return items[item_id] if __name__ == "__main__": uvicorn.run(app="20_union_list_dict:app", host="127.0.0.1", port=8080, reload=True, debug=True)

 

item_id = item1 的请求结果

 

item_id = item2 的请求结果

 

List

class Item(BaseModel):
name: str
description: str

items = [
{"name": "Foo", "description": "There comes my hero"},
{"name": "Red", "description": "It's my aeroplane", "size": 123}, # 多了个 size 字段
]

@app.get("/items/", response_model=List[Item])
async def read_items():
return items

  

正确传参的请求结果

返回的是一个数组

 

假设响应内容多了个 size

items[1] 多了个 size 字段,但因为响应模型并不包含 size,所以最终返回的数据也不会包含 size

 

假设响应内容不包含 description

raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Item
response -> 1 -> description
field required (type=value_error.missing)
  • 因为响应模型声明了 name、description 都是必传参数,假设不传就会报错
  • 但又因为是响应数据有问题,代表应用程序(服务端)有问题,所以客户端发送请求就会报 500

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: