前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >FastAPI学习-8.POST请求body中添加Field

FastAPI学习-8.POST请求body中添加Field

作者头像
上海-悠悠
发布2022-03-08 14:41:10
9770
发布2022-03-08 14:41:10
举报
文章被收录于专栏:从零开始学自动化测试

前言

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

Field 字段参数说明

关于 Field 字段参数说明

  • Field(None) 是可选字段,不传的时候值默认为None
  • Field(…) 是设置必填项字段
  • title 自定义标题,如果没有默认就是字段属性的值
  • description 定义字段描述内容
代码语言:javascript
复制
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

代码语言:javascript
复制
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 元数据。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-03-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 从零开始学自动化测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • Field 字段参数说明
  • 导入 Field
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档