我们都知道,去创建请求体,更新数据我们用PUT请求,我们去试着更新下数据。
我们有一组数据,我们要更新描述。
- from fastapi import FastAPI
- from typing import List, Optional
- from fastapi.encoders import jsonable_encoder
- from pydantic import BaseModel
-
- app = FastAPI()
-
-
- class Item(BaseModel):
- name: Optional[str] = None
- description: Optional[str] = None
- price: Optional[float] = None
- tax: float = 10.5
- tags: List[str] = []
-
- items = {
- "one": {
- "name": "apple", "price": 50.3
- }
- }
-
-
- @app.put("/items", response_model=Item)
- def upadte_item(name: str, item: Item):
- update_item_encoded = jsonable_encoder(item)
- items[name] = update_item_encoded
- return update_item_encoded
-
-
- @app.get("/items/{item_id}", response_model=Item)
- def read_item(item_id: str):
- return items[item_id]
获取下数据试试
更新下数据
更新部分数据时,可以在 Pydantic 模型的 .dict() 中使用 exclude_unset 参数。
比如,item.dict(exclude_unset=True)。我们去看我们实际的例子
- from fastapi import FastAPI
- from typing import List, Optional
- from fastapi.encoders import jsonable_encoder
- from pydantic import BaseModel
-
- app = FastAPI()
-
-
- class Item(BaseModel):
- name: Optional[str] = None
- description: Optional[str] = None
- price: Optional[float] = None
- tax: float = 10.5
- tags: List[str] = []
-
- items = {
- "one": {
- "name": "apple", "price": 50.3
- }
- }
-
-
- @app.put("/items", response_model=Item)
- def upadte_item(name: str, item: Item):
- stored_item_data = items[name]
- stored_item_model = Item(**stored_item_data)
- upadte_data = item.dict(exclude_unset=True)
- update_item = stored_item_model.copy(update=upadte_data)
- items[name] = jsonable_encoder(update_item)
- print(items)
- return update_item
-
-
- @app.get("/items/{item_id}", response_model=Item)
- def read_item(item_id: str):
- return items[item_id]
我们去看下去后的效果
简而言之,更新部分数据做法: