입장부터 실전까지 FastAPI (14) - JSON 인코딩 호환성 및 업데이트 요청

데이터 형식 및 유형 문제를 위해 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转dict, datetime转str

이미지-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 인코더 기반)을 수행한 다음 데이터를 저장합니다.

이미지-20221203170414554

이미지-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 방법이 자주 사용됩니다.구체적인 프로세스에 대해서는 위 코드의 주석을 참조하십시오.

이미지-20221203170647405

이미지-20221203170709665


읽어 주셔서 감사합니다!

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

블로거의 개인 미니 프로그램에 오신 것을 환영합니다!

추천

출처blog.csdn.net/qq_45730223/article/details/128167238