• FastAPI 基础学习(十) Pydantic复杂模型


    作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

    一、Pydantic模型的附加信息

    与前面讲过的Query、Path、Body类似,我们也可以为Pydantic模型添加附加信息,基于模块Field。

    1、导入Field模块

    from pydantic import BaseModel, Field

    2、声明模型属性

    class Item(BaseModel):
        name: str
        description: str = Field(None, title="The description of the item", max_length=300)
        price: float = Field(..., gt=0, description="The price must be greater than zero")
        tax: float = None

    Field模块的参数与Query、Path、Body等相同。

    完整示例:

    from fastapi import Body, FastAPI
    from pydantic import BaseModel, Field
    
    app = FastAPI()
    
    
    class Item(BaseModel):
        name: str
        description: str = Field(None, title="The description of the item", max_length=300)
        price: float = Field(..., gt=0, description="The price must be greater than zero")
        tax: float = None
    
    
    @app.put("/items/{item_id}")
    async def update_item(*, item_id: int, item: Item = Body(..., embed=True)):
        results = {"item_id": item_id, "item": item}
        return results

    、Pydantic嵌套模型

    任意嵌套深度的Pydantic模型,我们都可以进行定义、校验、自动文档化和灵活使用

    1、模型的属性可以是数据集合类型

    比如list,dict,tuple,set等等。

    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
        tags: list = []
    from typing import List
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
        tags: List[str] = []
    from typing import Set
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
        tags: Set[str] = set()

    我们也可以直接定义一个字典类型的body,通常指定了键和值的数据类型。

    from typing import Dict
    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.post("/index-weights/")
    async def create_index_weights(weights: Dict[int, float]):
        return weights

    2、嵌套模型

    每一个Pydantic模型的属性都有一个类型,这个类型也可以是另一个Pydantic模型。

    from typing import Set
    
    from fastapi import FastAPI
    from pydantic import BaseModel
    
    app = FastAPI()
    
    
    class Image(BaseModel):
        url: str
        name: str
    
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
        tags: Set[str] = []
        image: Image = None
    
    
    @app.put("/items/{item_id}")
    async def update_item(*, item_id: int, item: Item):
        results = {"item_id": item_id, "item": item}
        return results

    FastAPI期望的Request Body内容格式如下:

    {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2,
        "tags": ["rock", "metal", "bar"],
        "image": {
            "url": "http://example.com/baz.jpg",
            "name": "The Foo live"
        }
    }

    我们也可以把Pydantic模型作为list、set等集合类型的元素类型。

    from typing import List, Set
    from fastapi import FastAPI
    from pydantic import BaseModel, HttpUrl
    
    app = FastAPI()
    
    
    class Image(BaseModel):
        url: HttpUrl
        name: str
    
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
        tags: Set[str] = []
        images: List[Image] = None
    
    
    @app.put("/items/{item_id}")
    async def update_item(*, item_id: int, item: Item):
        results = {"item_id": item_id, "item": item}
        return results

    这里FastAPI期望的Request Body内容格式如下:

    {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2,
        "tags": [
            "rock",
            "metal",
            "bar"
        ],
        "images": [
            {
                "url": "http://example.com/baz.jpg",
                "name": "The Foo live"
            },
            {
                "url": "http://example.com/dave.jpg",
                "name": "The Baz"
            }
        ]
    }

    3、深层嵌套模型

    我们可以定义任意深度的嵌套模型,如下示例:

    from typing import List, Set
    
    from fastapi import FastAPI
    from pydantic import BaseModel, HttpUrl
    
    app = FastAPI()
    
    
    class Image(BaseModel):
        url: HttpUrl
        name: str
    
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
        tags: Set[str] = []
        images: List[Image] = None
    
    
    class Offer(BaseModel):
        name: str
        description: str = None
        price: float
        items: List[Item]
    
    
    @app.post("/offers/")
    async def create_offer(*, offer: Offer):
        return offer
  • 相关阅读:
    MyEclipse 2016CI破解版for Mac
    关于Mac系统中my sql 和navicat for mysql 的连接问题。
    二分总结
    递推总结
    区间DP学习笔记 6/20
    搜索考试
    模板整理
    防线 2020/3/31
    JS 循环遍历JSON数据
    pm am 12小时格式化
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/12923751.html
Copyright © 2020-2023  润新知