FastAPI从入门到实战(7)——请求体函数的参数设置

上一篇记录了FastAPI中声明请求体的相关内容,本文记录一下零碎的函数特性和参数特性相关内容。

Pydantic schema_extra

可以使用 Configschema_extra 为Pydantic模型声明一个示例:

class City(BaseModel):
    country:str = "中国"
    provence:str = Field(...,example = "四川") # Field可以定义请求体的格式和类型
    citys: Optional[List] = None
    population: int = Field(default=None,title="人口数",ge=1000)

    class Config:
        schema_extra = {
            "example":{
                "country":"中国",
                "provence":"四川",
                "citys":["绵阳","成都","遂宁","..."],
                "population":66666666
            }
        }

image-20221125215909375

Field参数设置

fieldPathQueryBody可以设置default、title等信息;具体参看源码;

def Field(
    default: Any = Undefined,
    *,
    default_factory: Optional[NoArgAnyCallable] = None,
    alias: str = None,
    title: str = None,
    description: str = None,
    exclude: Union['AbstractSetIntStr', 'MappingIntStrAny', Any] = None,
    include: Union['AbstractSetIntStr', 'MappingIntStrAny', Any] = None,
    const: bool = None,
    gt: float = None,
    ge: float = None,
    lt: float = None,
    le: float = None,
    multiple_of: float = None,
    allow_inf_nan: bool = None,
    max_digits: int = None,
    decimal_places: int = None,
    min_items: int = None,
    max_items: int = None,
    unique_items: bool = None,
    min_length: int = None,
    max_length: int = None,
    allow_mutation: bool = True,
    regex: str = None,
    discriminator: str = None,
    repr: bool = True,
    **extra: Any,
)

Body参数设置

BodyPathQuery是一个性质的,分别声明请求体、路径参数、查询参数

# 无 Body 额外参数
@app04.post("/stu04/notbodyfield")
def stu04_not_bdy_field(
        param:Dog
):
    return param


# Body 额外参数
@app04.post("/stu04/bodyfield")
def stu04_bdy_field(
        param:Dog = Body(
            example={
                "name":"小七",
                "age":15,
                "varieties":"泰迪",
                "birthday":date.today()
            }
        )
):
    return param

image-20221125220527054

image-20221125220553476

其他数据类型

目前用的都是常见的数据类型,包括int、float、str、bool等等;

也可以使用其他数据类型,几乎所有Pydantic支持的数据类型都可以:Pydantic-字段类型

也可以参看源码:

__all__ = [
    # annotated types utils
    'create_model_from_namedtuple',
    'create_model_from_typeddict',
    # dataclasses
    'dataclasses',
    # class_validators
    'root_validator',
    'validator',
    # config
    'BaseConfig',
    'ConfigDict',
    'Extra',
    # decorator
    'validate_arguments',
    # env_settings
    'BaseSettings',
    # error_wrappers
    'ValidationError',
    # fields
    'Field',
    'Required',
    # main
    'BaseModel',
    'create_model',
    'validate_model',
    # network
    'AnyUrl',
    'AnyHttpUrl',
    'FileUrl',
    'HttpUrl',
    'stricturl',
    'EmailStr',
    'NameEmail',
    'IPvAnyAddress',
    'IPvAnyInterface',
    'IPvAnyNetwork',
    'PostgresDsn',
    'CockroachDsn',
    'AmqpDsn',
    'RedisDsn',
    'MongoDsn',
    'KafkaDsn',
    'validate_email',
    # parse
    'Protocol',
    # tools
    'parse_file_as',
    'parse_obj_as',
    'parse_raw_as',
    'schema_of',
    'schema_json_of',
    # types
    'NoneStr',
    'NoneBytes',
    'StrBytes',
    'NoneStrBytes',
    'StrictStr',
    'ConstrainedBytes',
    'conbytes',
    'ConstrainedList',
    'conlist',
    'ConstrainedSet',
    'conset',
    'ConstrainedFrozenSet',
    'confrozenset',
    'ConstrainedStr',
    'constr',
    'PyObject',
    'ConstrainedInt',
    'conint',
    'PositiveInt',
    'NegativeInt',
    'NonNegativeInt',
    'NonPositiveInt',
    'ConstrainedFloat',
    'confloat',
    'PositiveFloat',
    'NegativeFloat',
    'NonNegativeFloat',
    'NonPositiveFloat',
    'FiniteFloat',
    'ConstrainedDecimal',
    'condecimal',
    'ConstrainedDate',
    'condate',
    'UUID1',
    'UUID3',
    'UUID4',
    'UUID5',
    'FilePath',
    'DirectoryPath',
    'Json',
    'JsonWrapper',
    'SecretField',
    'SecretStr',
    'SecretBytes',
    'StrictBool',
    'StrictBytes',
    'StrictInt',
    'StrictFloat',
    'PaymentCardNumber',
    'PrivateAttr',
    'ByteSize',
    'PastDate',
    'FutureDate',
    # version
    'compiled',
    'VERSION',
]

源码

# -*- coding: utf-8 -*-
# @Time: 2022/11/25 21:21
# @Author: MinChess
# @File: stu04.py
# @Software: PyCharm
from fastapi import APIRouter,Body
from pydantic import BaseModel,Field
from typing import Optional,List

from datetime import date

app04 = APIRouter()

# 创建一个数据模型
class City(BaseModel):
    country:str = "中国"
    provence:str = Field(...,example = "四川") # Field可以定义请求体的格式和类型
    citys: Optional[List] = None
    population: int = Field(default=None,title="人口数",ge=1000)

    class Config:
        schema_extra = {
            "example":{
                "country":"中国",
                "provence":"四川",
                "citys":["绵阳","成都","遂宁","..."],
                "population":66666666
            }
        }

# Pydantic schema_extra

@app04.post("/stu04/schemaextra")
def stu04_schema_extra(
        city:City
):
    return city

# Field 的附加参数
class Dog(BaseModel):
    name:str = Field(example = "小黑")
    age:int = Field(...,description="狗的年龄",gt=0,le=20)
    varieties:str = Field(default="拉布拉多",title="狗的品种")
    birthday:date

# 无 Body 额外参数
@app04.post("/stu04/notbodyfield")
def stu04_not_bdy_field(
        param:Dog
):
    return param


# Body 额外参数
@app04.post("/stu04/bodyfield")
def stu04_bdy_field(
        param:Dog = Body(
            example={
                "name":"小七",
                "age":15,
                "varieties":"泰迪",
                "birthday":date.today()
            }
        )
):
    return param

欢 迎 关 注 博 主 个 人 小 程 序!
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九陌斋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值