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


    前言

    有多个模型,且请求/响应需要声明多个模型的时候,可以根据不同使用场景结合 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

  • 相关阅读:
    python之openpyxl模块
    jquery实现轮播图
    Css进阶练习(实现抽屉网样式布局)
    python之UnittTest模块
    zkClient的使用
    Watcher、ZK状态、事件类型 ,权限
    java 操作zookeeper
    Zookeeper简介
    RocketMq顺序消费
    RocketMq --consumer自动实现负载均衡
  • 原文地址:https://www.cnblogs.com/poloyy/p/15318738.html
Copyright © 2020-2023  润新知