针对数据格式和类型问题,fastapi内置了一个很好的转换器,本文就相关内容主要记录编码和请求更新相关内容;

json兼容编码器

class Animal(BaseModel):
    name: str = "JACK"
    age: int = 21
    birthday: datetime = datetime.now()


@app08.put("/stu08/json_update/")
def stu07_update(animal: Animal):
    print("animal__type:", type(animal), "animal:", animal)
    json_data = jsonable_encoder(animal)
    print("animal__type:", type(json_data), "animal:", json_data)
    return animal

# 输出结果
# animal__type: <class 'stu.stu07.Animal'> animal: name='JACK' age=21 birthday=datetime.datetime(2022, 12, 2, 18, 31, 38, 373484)
# animal__type: <class 'dict'> animal: {'name': 'JACK', 'age': 21, 'birthday': '2022-12-02T18:31:38.373484'}

现在我们的请求大多都是Pydantic模型类的,在实际的应用中并不会兼容,例如存储到数据库中,利用fastapi内置的jsonable_encoder()函数就能很好的解决相关的问题;会进行类型的转换,例如pydantic转dictdatetime转str

image-20221202183156868

PUT请求更新数据

class City(BaseModel):
    province: Optional[str] = Field("重庆")
    cityname: Optional[str] = Field("重庆")
    gdp: Optional[float] = Field(236542.25)
    towns: Optional[List[str]] = Field(["奉节","云阳","万州"])
    population: Optional[int] = Field(562312)


cityitem = {
    1: {
        "province": "四川",
        "cityname": "成都",
        "gdp": 12653.56,
    },
    2: {
        "province": "山西",
        "cityname": "太原",
        "gdp": 10003.56,
        "towns": ["清徐", "小店", "迎泽"],
        "population": 556565
    },
    3: {
        "province": "吉林",
        "cityname": "长春",
        "gdp": 10253.85,
        "towns": [],
        "population": 54160
    }
}


@app08.put("/stu08/cityput/{cityid}")
async def stu08_city_put(
        city: City = Body(default={
        "province": "湖南",
        "cityname": "长沙",
        "gdp": 15553.85,
        "towns": ["安化"],
        "population": 236160
    }),
        cityid: int = Path(ge=1, le=3),
):
    update_city = jsonable_encoder(city)
    cityitem[cityid] = update_city
    print(cityitem)
    return update_city

PUT更新数据很简单,接受一个同类型的请求体,将接收的请求体进行解码,就是进行对应的类型转换(基于上面的JSON编码器),然后进行数据存储:

image-20221203170414554

image-20221203170443104

PATCH请求更新数据

@app08.patch("/stu08/citypatch/{cityid}")
async def stu08_city_patch(
        city: City,
        cityid: int = Path(ge=1, le=3),
):
    city_item_data = cityitem[cityid] # 获取cityitem内对应id的数据
    city_item_model = City(**city_item_data) # 将获取到的数据转为City类型
    city_item_update = city.dict(exclude_unset=True) # 将获取的数据设置为不包含默认值的字典
    city_item_update_result = city_item_model.copy(update=city_item_update) # 使用pydantic方法进行数据更新
    cityitem[cityid] = jsonable_encoder(city_item_update_result) # 将更新后的数据进行编码并放回cityitem
    print(cityitem)
    return city_item_update_result

这个就是部分更新,了解方法即可,实际应用中,还是PUT方法用的多,具体过程参看上面代码的注释;

image-20221203170647405

image-20221203170709665


感谢阅读!

九陌斋地址:https://blog.jiumoz.com/archives/fastapi-cong-ru-men-dao-shi-zhan-14json-bian-ma-jian-rong-yu-geng-xin-qing-qiu

欢 迎 关 注 博 主 个 人 小 程 序!