章节代码(fastapi部分)
from enum import Enum
from typing import Optional, List
from datetime import date
from fastapi import APIRouter, Path, Query, Cookie, Header
from pydantic import BaseModel, Field
app01 = APIRouter()
"""
Path Parameters and Number Validations路径参数和数字验证
"""
@app01.get("/parameters")
def path_params01():
return {"message": "This is a messaget"}
@app01.get("/{parameters}")
def path_params01(parameters: str):
return {"message": parameters}
class CityName(str, Enum):
Beijing = "Beijing china"
Shanghai = "Shanghai China"
@app01.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"}
@app01.get("/files/{file_path:path}")
def filepath(file_path: str):
return f"The file path is {file_path}"
@app01.get("/path_/{num}")
def path_params_validate(
num: int = Path(..., title="Your number", description="路径参数校验大于1小于10", ge=1, le=10)):
return num
"""
查询参数和字符串验证
"""
@app01.get("/query/")
def page_limit(page: int = 1, limit: Optional[int] = None):
if limit:
return {"page": page, "limit": limit}
return {"page": page}
@app01.get("/query/bool/conversion/")
def type_conversion(param: bool = False):
return param
@app01.get("/query/validations/")
def query_params_validate(
value: str = Query(..., min_length=8, max_length=16, regex="^a"),
values: List[str] = Query(default=["v1", "v2"], alias="alias_name")):
return value, values
"""Request Body and Fields请求体和字段"""
class CityInfo(BaseModel):
city_name: str = Field(..., example='城市名称')
country_name: Optional[str] = None
population: int = Field(default=800, description='城市人口', ge=800)
class Config:
schema_extra = {
'example': {
'city_name': 'Shanghai',
'country_name': 'China',
'population': 36648000,
}
}
@app01.post('/city/')
async def city_info(city: CityInfo):
return city.dict()
"""混合参数"""
@app01.put('/city_alter/{city_name}')
async def city_alter(
city_name: str,
city1: CityInfo,
city2: CityInfo,
all_population: int = Query(default=140000000, description='国家总人口')
):
if city_name == 'Shanghai':
return {
'city_name': 'Shanghai',
'country_name': 'China',
'population': 36648000,
'all_popuplation': all_population
}
return city1.dict(), city2.dict()
"""嵌套请求体"""
class Data(BaseModel):
city_list: List[CityInfo] = None
total_population: int = Field(description='人口总数', default=1200000)
date: date
@app01.post('/data/')
def get_data(data: Data):
return data.dict()
"""cookie 和 header参数"""
@app01.get("/cookie/")
def cookie(cookie_id: Optional[str] = Cookie(None)):
return {"cookie_id": cookie_id}
@app01.get("/header/")
def header(user_agent: Optional[str] = Header(None, convert_underscores=True), x_token: List[str] = Header(None)):
"""
有些HTTP代理和服务器是不允许在请求头中带有下划线的,所以Header提供convert_underscores属性让设置将下划线转换为‘-’
:param user_agent: convert_underscores=True 会把user_agent 变成 user-agent
:param x_token : x_token是包含多个值的列表
: return :
"""
return {"User-Agent": user_agent, "x_token": x_token}