データ形式と型の問題については、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
。
データを更新するための 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 エンコーダーに基づいて)、データを保存します。
データを更新するための 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 メソッドがよく使われます 具体的な処理については上記コードのコメントを参照してください;
読んでくれてありがとう!
Jiumozhai アドレス: https://blog.jiumoz.com/archives/fastapi-cong-ru-men-dao-shi-zhan-14json-bian-ma-jian-rong-yu-geng-xin-qing-qiu