上一篇记录了FastAPI中声明请求体的相关内容,本文记录一下零碎的函数特性和参数特性相关内容。
Pydantic schema_extra
可以使用 Config
和 schema_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
}
}
Field参数设置
field
同Path
、Query
、Body
可以设置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参数设置
Body
和Path
、Query
是一个性质的,分别声明请求体、路径参数、查询参数
# 无 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
其他数据类型
目前用的都是常见的数据类型,包括
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
评论区