zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    84最佳买卖股票时机含冷冻期(309)
    83 不同路径 II(63)
    82同路径(62)
    模块与包
    名称空间与作用域
    函数的参数
    函数对象
    函数继续学习中
    python学习day3-上午
    第一个完成程序:通过文件实现注册登录
  • 原文地址:https://www.cnblogs.com/poloyy/p/15318738.html
Copyright © 2011-2022 走看看