• FastAPI学习8.POST请求body中添加Field 上海


    前言

    与使用 Query、Path 和 Body 在路径操作函数中声明额外的校验和元数据的方式相同,你可以使用 Pydantic 的 Field 在 Pydantic 模型内部声明校验和元数据。

    Field 字段参数说明

    关于 Field 字段参数说明

    • Field(None) 是可选字段,不传的时候值默认为None
    • Field(...) 是设置必填项字段
    • title 自定义标题,如果没有默认就是字段属性的值
    • description 定义字段描述内容
    from pydantic import BaseModel, Field
    
    
    class Item(BaseModel):
        name: str
        description: str = Field(None,
                                 title="The description of the item",
                                 max_length=10)
        price: float = Field(...,
                             gt=0,
                             description="The price must be greater than zero")
        tax: float = None
    
    
    a = Item(name="yo yo",
             price=22.0,
             tax=0.9)
    print(a.dict())  # {'name': 'yo yo', 'description': None, 'price': 22.0, 'tax': 0.9}
    

    导入 Field

    是从 pydantic 导入 Field

    from typing import Optional
    
    from fastapi import Body, FastAPI
    from pydantic import BaseModel, Field
    
    app = FastAPI()
    
    
    class Item(BaseModel):
        name: str
        description: Optional[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: Optional[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
    

    注意,Field 是直接从 pydantic 导入的,而不是像其他的(Query,Path,Body 等)都从 fastapi 导入。

    总结
    你可以使用 Pydantic 的 Field 为模型属性声明额外的校验和元数据。
    你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。

  • 相关阅读:
    [zjoi]青蛙的约会_扩展欧几里德
    [coci2012]覆盖字符串 AC自动机
    出题日志
    [zjoi2003]密码机
    矩阵乘法
    洛谷 P1064 金明的预算方案
    洛谷 P1656 炸铁路
    洛谷 P1049 装箱问题
    最长上升子序列(LIS)与最长公共子序列(LCS)
    求最大公约数与最小公倍数
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15962297.html
Copyright © 2020-2023  润新知