FastAPI学习笔记(一)-8.请求体和字段验证
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ''' 2 @author:invoker 3 @project:fastapi202108 4 @file: chapter033.py 5 @contact:invoker2021@126.com 6 @descript: 7 @Date:2021/8/6 8:32 8 @version: Python 3.7.8 9 ''' 10 11 from fastapi import APIRouter 12 from pydantic import BaseModel, Field 13 14 app033 = APIRouter() 15 16 """ 17 3.3 请求体+字段验证 18 """ 19 20 21 class CityInfo(BaseModel): 22 name: str = Field(..., example='wuhan1',title='城市名称') # Field后三个点,没有默认值表示必填项 23 country: str = Field(..., title='国家名称') # 没有默认值,必填项 24 country_code: str = Field(default=None, title='国家编码') # 有默认值为None,表示选填项 25 country_population: int = Field(default=800, title='人口数量', description='国家人口数量', ge=800) 26 27 # 有默认值default=800表示选填项 28 29 # 这个config并没有什么效果 30 # 写成Config就有效果 31 class Config: 32 schema_extra = { 33 "example": { 34 "name": "Wuhan", 35 "country": "China", 36 "country_code": "CN", 37 "country_population": 10000000 38 } 39 } 40 41 42 @app033.post("/request_body/city") 43 async def city_info(city: CityInfo): 44 print(city.name, city.country) # 打印部分在控制台展示 45 return city.dict() # 返回值在在线文档显示
class Config:
schema_extra = {
"example": {
"name": "Wuhan",
"country": "China",
"country_code": "CN",
"country_population": 10000000
}
}
这块代码将是example value,在线接口文档会展示:
class CityInfo(BaseModel):
name: str = Field(..., example='wuhan1',title='城市名称') # Field后三个点,没有默认值表示必填项
country: str = Field(..., title='国家名称') # 没有默认值,必填项
country_code: str = Field(default=None, title='国家编码') # 有默认值为None,表示选填项
country_population: int = Field(default=800, title='人口数量', description='国家人口数量', ge=800)
Field中设置的example,title,description等信息在schema中展示
请求体中字段的校验用到了Field类
from pydantic import BaseModel, Field
本文来自博客园,作者:kaer_invoker,转载请注明原文链接:https://www.cnblogs.com/invoker2021/p/15107093.html