FastAPI from entry to actual combat (14) - JSON encoding compatibility and update request

For data format and type issues, fastapi has a built-in good converter. This article mainly records the relevant content of encoding and request update related content;

json compatible encoder

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'}

Now most of our requests are Pydanticmodel types, which are not compatible in actual applications, such as storing them in the database, and using the built-in jsonable_encoder()functions of fastapi can solve related problems well; they will perform type conversion, for example pydantic转dict, datetime转str

image-20221202183156868

PUT request to update data

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

PUTUpdating data is very simple. Accept a request body of the same type, decode the received request body, and perform corresponding type conversion (based on the JSON encoder above), and then store the data:

image-20221203170414554

image-20221203170443104

PATCH request to update data

@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

This is a partial update, just understand the method. In practical applications, the PUT method is often used. For the specific process, please refer to the comments of the above code;

image-20221203170647405

image-20221203170709665


Thanks for reading!

Jiumozhai address: https://blog.jiumoz.com/archives/fastapi-cong-ru-men-dao-shi-zhan-14json-bian-ma-jian-rong-yu-geng-xin-qing-qiu

Welcome to follow the blogger's personal mini program!

Guess you like

Origin blog.csdn.net/qq_45730223/article/details/128167238