深入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 模型继承定义的基类。

相关推荐
IVEN_11 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang12 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮13 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling13 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮16 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽16 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers