3-路径参数和数字验证
添加路由接口文件
# qpp01/route.py
from fastapi import APIRouter
app03 = APIRouter()
定义路由函数
# 不传参路由
@app03.get("/path/parameters")
def path_params01():
return {"message": "This is a message"}
# 传参路由
@app03.get("/path/{parameters}") # 函数的顺序就是路由的顺序
def path_prams02(parameters: str):
return {"message": parameters}
注意:
函数的顺序就是路由的顺序,相同的路由优先匹配上面的函数接口
枚举类型参数
from enum import Enum
class CityName(str, Enum):
Beijing = "Beijing China"
Shanghai = "Shanghai China"
@app03.get("/enum/{city}") # 枚举类型的参数
async def latest(city: CityName):
if city == CityName.Shanghai:
return {"city_name": city, "confirmed": 1492, "death": 7}
if city == CityName.Beijing:
return {"city_name": city, "confirmed": 971, "death": 9}
return {"city_name": city, "latest": "unknown"}
- 使用枚举类可以让文档中,参数变成可选的下拉框
- 不使用不会报错,文档中参数需要填写
通过path parameters传递文件路径
@app03.get("/files/{file_path:path}") # 通过path parameters传递文件路径
def filepath(file_path: str):
return f"The file path is {file_path}"
- f模式表示在打括号内可以写python表达式,和react里面的打括号效果一样
路径参数验证
@app03.get("/path_/{num}")
def path_params_validate(
num: int = Path(default=..., title="Your Number", description="不可描述", ge=1, le=10),
):
"""
defaylt:默认参数,在路径参数中是必须的,所有一般设置为...
title:标题
description:描述
"""
return num
查询参数
@app03.get("/query")
def page_limit(page: int = 1, limit: Optional[int] = None): # 给了默认值就是选填的参数,没给默认值就是必填参数
if limit:
return {"page": page, "limit": limit}
return {"page": page}
查询参数验证
@app03.get("/query/validations") # 长度+正则表达式验证,比如长度8-16位,以a开头。其它校验方法看Query类的源码
def query_params_validate(
value: str = Query(..., min_length=8, max_length=16, regex="^a"), # ...换成None就变成选填的参数
values: List[str] = Query(["v1", "v2"], alias="alias_name")
): # 多个查询参数的列表。参数别名
return value, values
表单参数
@app04.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)): # 定义表单参数
"""用Form类需要pip install python-multipart; Form类的元数据和校验方法类似Body/Query/Path/Cookie"""
return {"username": username}
布尔类型转换
@app03.get("/query/bool/conversion") # bool类型转换:yes on 1 True true会转换成true, 其它为false或者报错
def type_conversion(param: bool = False):
return param
请求体和字段
class CityInfo(BaseModel):
name: str = Field(..., example="Beijing") # example是注解的作用,值不会被验证
country: str
country_code: str = None # 给一个默认值
country_population: int = Field(default=800, title="人口数量", description="国家的人口数量", ge=800)
class Config:
schema_extra = {
"example": {
"name": "Shanghai",
"country": "China",
"country_code": "CN",
"country_population": 1400000000,
}
}
@app03.post("/request_body/city")
def city_info(city: CityInfo):
print(city.name, city.country) # 当在IDE中输入city.的时候,属性会自动弹出
return city.dict()
多参数混合
@app03.put("/request_body/city/{name}")
def mix_city_info(
name: str,
city01: CityInfo,
city02: CityInfo, # Body可以是多个的
confirmed: int = Query(ge=0, description="确诊数", default=0),
death: int = Query(ge=0, description="死亡数", default=0),
):
if name == "Shanghai":
return {"Shanghai": {"confirmed": confirmed, "death": death}}
return city01.dict(), city02.dict()
数据格式嵌套的请求体
class Data(BaseModel):
city: List[CityInfo] = None # 这里就是定义数据格式嵌套的请求体
date: date # 额外的数据类型,还有uuid datetime bytes frozenset等,参考:https://fastapi.tiangolo.com/tutorial/extra-data-types/
confirmed: int = Field(ge=0, description="确诊数", default=0)
deaths: int = Field(ge=0, description="死亡数", default=0)
recovered: int = Field(ge=0, description="痊愈数", default=0)
@app03.put("/request_body/nested")
def nested_models(data: Data):
return data
总结
- 在使用请求体校验的时候使用Field交要
- 查询参数校验Query
- 路径参数校验Path