用 PUT
更新数据
把输入数据转换为 JSON 数据(例如,使用 NoSQL 数据库时),可以使用 jsonable_encoder
。例如,把 datetime
转换为 str
PUT
用于接收替换现有数据的数据
更新数据示例
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str | None = None
description: str | None = None
price: float | None = None
tax: float = 10.5
tags: list[str] = []
class Config:
schema_extra = {
"example": {
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
}
}
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: str):
return items[item_id]
@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
update_item_encoded = jsonable_encoder(item)
items[item_id] = update_item_encoded
print(items[item_id])
return update_item_encoded
注意
用 PUT
把数据项 bar
更新为以下内容时:
{
"name": "Barz",
"price": 3,
"description": None,
}
因为上述数据未包含已存储的属性 "tax": 20.2
,新的输入模型会把 "tax": 10.5
作为默认值。
因此,本次操作会把 tax
的值更新为 10.5
。
用 PATCH
进行部分更新
@app.patch("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
print("使用patch方法更新数据")
stored_item_data = items[item_id]
stored_item_model = Item(**stored_item_data)
update_data = item.dict(exclude_unset=True)
updated_item = stored_item_model.copy(update=update_data)
items[item_id] = jsonable_encoder(updated_item)
print("更新后的数据为:", items[item_id])
return updated_item
简而言之,更新部分数据应:
- 使用
PATCH
,而不是 PUT
(可选,也可以用 PUT
) - 提取存储的数据
- 把数据放入 Pydantic 模型
- (使用exclude_unset参数)生成不含输入模型默认值的dict
- 只更新用户设置过的值,不用模型中的默认值覆盖已存储的值
- (使用
update
参数)为已存储的模型创建副本,用接收的数据更新其属性 - 把模型副本转换为可存入数据库的形式(比如,使用jsonable_encoder)
- 这种方式与 Pydantic 模型的
.dict()
方法类似,但能确保把值转换为适配 JSON 的数据类型,例如, 把 datetime
转换为 str
- 把数据保存至数据库
- 返回更新后的模型
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)