赞
踩
from typing import Optional, List from datetime import date from fastapi import APIRouter, Query, Body from pydantic import Field, BaseModel app05 = APIRouter() class CityInfo(BaseModel): name: str = Field(..., example="Beijing") country: str country_code: str = None country_population: int = Field(800, title="人口数量", description="国家的人口数量", ge=800) class Config: schema_extra = { "example": { "name": "Shanghai", "country": "China", "country_code": "CN", "country_population": 1400000000, } } @app05.post("/request_body/city") def city_info(city: CityInfo): print(city.name, city.country) # 当在IDE中输入city.的时候,属性会自动弹出 return city.dict() """Request Body + Path parameters + Query parameters 多参数混合""" @app05.put("/request_body/city/{name}") def mix_city_info( name: str, city01: CityInfo, city02: CityInfo, confirmed: int = Query(0, description="确诊数", ge=0), death: int = Query(0, description="死亡数", ge=0) ): if name == "Shanghai": return {"Shanghai": {"confirmed": confirmed, "death": death}} return city01.dict(), city02.dict() @app05.put("/request_body/multiple/parameters") def body_multiple_parameters( # 当只有一个Body参数的时候,embed=True表示请求体参数嵌套。多个Body参数默认就是嵌套的 city: CityInfo = Body(..., embed=True), confirmed: int = Query(default=0, description="确诊数", ge=0), death: int = Query(0, description="死亡数", ge=0) ): print(city) print(type(city)) print(f"{city.name} 确诊数:{confirmed} 死亡数:{death}") return city.dict() """Request Body - Nested Models 数据格式嵌套的请求体""" 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) @app05.put("/request_body/nested") def nested_models(data: Data): return data
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。