FastAPI from entry to actual combat (7) - parameter setting of request body function

The previous article recorded the relevant content of the declared request body in FastAPI. This article records the relevant content of fragmentary function characteristics and parameter characteristics.

Pydantic schema_extra

An example can be declared for a Pydantic model using Configand :schema_extra

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 parameter setting

fieldSame as Path, Query, Bodyyou can set default, title and other information; see the source code for details;

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 parameter settings

Bodyand and Pathare Queryof the same nature, respectively declaring the request body, path parameters, and query parameters

# 无 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

other data types

Common data types are currently used, including, int、float、str、booletc.;

Other data types can also be used, almost all data types supported by Pydantic: Pydantic-field-type

You can also refer to the source code:

__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',
]

source code

# -*- 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

Welcome to follow the blogger's personal mini program!

Guess you like

Origin blog.csdn.net/qq_45730223/article/details/128070180