文章目录
- 1. PUT 更新
- 2. 用 PATCH 进行部分更新
learn from https://fastapi.tiangolo.com/zh/tutorial/body-updates/
1. PUT 更新
- 注意,put 没有指定的值,会被重置为默认值
from typing import List, Optionalfrom fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: Optional[str] = Nonedescription: Optional[str] = Noneprice: Optional[float] = Nonetax: float = 10.5tags: 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}")
async def update_item(item_id: str, item: Item):update_item_encoded = jsonable_encoder(item)items[item_id] = update_item_encodedreturn jsonable_encoder(items)
2. 用 PATCH 进行部分更新
- 只发送 要更新的数据,其余数据保持不变
- 可以在
Pydantic
模型的.dict()
中使用exclude_unset
参数:排除没有设置的参数(默认值的参数) .copy()
为已有模型创建副本,调用update
参数更新数据
from typing import List, Optionalfrom fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: Optional[str] = Nonedescription: Optional[str] = Noneprice: Optional[float] = Nonetax: float = 10.5tags: 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) # 原来的数据生成新的modelupdate_data = item.dict(exclude_unset=True) # 原来的model除去未设置的字段updated_item = stored_item_model.copy(update=update_data)# 创建新的model副本,更新数据(只更新设置的字段)items[item_id] = jsonable_encoder(updated_item) # 模型副本转换为可存入数据的形式,存入数据库return updated_item