使用PUT更新替换
HTTP PUT操作可用于更新,
你可以使用jsonable_encoder来转换输入的数据为可以使用json存储的数据。
(eg:NoSQL Database)
from typing import List
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str = None
description: str = None
price: float = None
tax: float = 10.5
tags: List[str] = []
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
return update_item_encoded
PUT是用来将接受的数据替换已存在的数据。
使用PATCH实现部分更新
使用PATCH意味着你可以只发送想要更新的数据,其他的不变。
但是这个方法很少使用,更多的使用put方法。
pydantic参数exclude_unset的使用
如果你只想部分的更新,这个参数将非常的实用。
使用方法:item.dict(exclude_unseet=True)
它将会生成字典,这个字典只包括已传入的值,而排除默认值。
from typing import List
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str = None
description: str = None
price: float = None
tax: float = 10.5
tags: List[str] = []
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.patch("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
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)
return updated_item
pydantic参数update的使用
现在,你可以创建一个已存在模型的拷贝,使用.copy()并传入update参数,值为需要更新的数据字典。
updated_item = stored_item_model.copy(update=update_data)
407



被折叠的 条评论
为什么被折叠?



