深入FastAPI:掌握使用多个关联模型的高级用法[Union类型]

在FastAPI中,响应模型可以声明为Union类型,这允许你为同一个端点定义多种可能的响应模型。这种灵活性使得API可以根据不同的情况返回不同类型的数据结构。

例如,根据请求中的查询参数或数据库中的数据,一个API端点可能有时返回一个用户模型,有时返回一个订单模型。使用Union类型,你可以为这些不同的响应定义一个统一的响应模型,从而提高代码的可维护性和API的可用性。这种方法也有助于在API文档中清晰地展示各种可能的响应类型,为开发者和API用户提供更好的指导。

回忆response_model模型

···

···

UNION

响应类可以声明为多种类型,Union 类型就是其中的一种,从多个响应类内输出一个

python 复制代码
from typing import Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# 定义基础项目模型
class BaseItem(BaseModel):
    description: str  # 项目的描述
    type: str  # 项目的类型

# 定义特定类型的项目模型
class CarItem(BaseItem):
    type: str = "car"  # 车辆类型的项目

class PlaneItem(BaseItem):
    type: str = "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,
    },
}

# 定义路由,根据item_id返回对应的项目信息
@app.get("/items/{item_id}", response_model=Union[PlaneItem, CarItem])
async def read_item(item_id: str) -> Union[PlaneItem, CarItem]:  # 根据item_id获取项目信息
    return items[item_id]

在这个代码中,我们定义了两个模型 CarItemPlaneItem,它们都继承自 BaseItem。我们还定义了一个字典 items 来模拟数据库中的数据。

read_item 函数通过 item_id 参数来获取相应的项目信息,并返回一个 Union[PlaneItem, CarItem] 类型的对象。这意味着函数的返回值可以是 PlaneItem 类型或者 CarItem 类型,这取决于 items 字典中 type 字段的值。

当我们访问 /items/item1 时,输出结果将是:

json 复制代码
{
  "description": "All my friends drive a low rider",
  "type": "car"
}

而当我们访问 /items/item2 时,输出结果将是:

json 复制代码
{
  "description": "Music is my aeroplane, it's my aeroplane",
  "type": "plane",
  "size": 5
}

这些输出结果由FastAPI根据请求的 item_id 参数和 items 字典中的数据自动生成。FastAPI会根据返回值的类型自动序列化为JSON格式。

针对不同场景,可以随意使用不同的 Pydantic 模型继承定义的基类。

相关推荐
做怪小疯子2 小时前
华为笔试0429
python·numpy
Warson_L2 小时前
Dictionary
python
寒山李白4 小时前
解决 python-docx 生成的 Word 文档打开时弹出“无法读取内容“警告
python·word·wps·文档·docx·qoder
2401_832365525 小时前
JavaScript中rest参数(...args)取代arguments的优势
jvm·数据库·python
Sirius.z5 小时前
第J3周:DenseNet121算法详解
python
2301_779622416 小时前
Go语言怎么用信号量控制并发_Go语言semaphore信号量教程【入门】
jvm·数据库·python
2301_766283446 小时前
c++如何将控制台输出保存到文件_cout重定向到txt【详解】
jvm·数据库·python
小康小小涵7 小时前
基于ESP32S3实现无人机RID模块底层源码编译
linux·开发语言·python
lzjava20247 小时前
Python的函数
开发语言·python
Awesome Baron8 小时前
skill、tool calling、MCP区别
开发语言·人工智能·python