Fastapi learning path (21) request body – update data

Time:2022-6-9

Series:

  Fastapi learning path (I) fastapi — high performance web development framework

  Fastapi learning path (II)

  Fastapi learning path (III)

  Fastapi learning path (IV)

  Fastapi learning path (V)

      Fastapi learning path (6) query parameters and string verification

  Fastapi learning path (VII) string verification

    Fastapi learning path (VIII) verification of path parameters and values

  Fastapi learning path (IX) how to handle multiple parameters in the request body?

  Fastapi learning path (x) fields of request body

      Fastapi learning path (11) request body nested model 

    Fastapi learning path (XII) interface several additional information and additional data types

      Fastapi learning path (13) cookie parameters, header parameters

    Fastapi learning path (XIV) response model

  Fastapi learning path (XV) response status code

    Fastapi learning path (16) form form

     Fastapi learning path (17) uploading files

     Fastapi learning path (18) forms and documents

  Fastapi learning path (19) handling errors

     Fastapi learning path (XX) interface document configuration

We all know that to create the request body and update the data, we use put to request, and we try to update the data.

We have a set of data, and we want to update the description.

from typing import List, Optional
from fastapi import FastAPI
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.2}
}
@app.put("/items/", response_model=Item)
def update_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]

Let’s go get it

 

Let’s update the data

 

Let’s update a nonexistent data

 

 

Some data can be updated in the pydantic model Use exclude in dict()_ Unset parameter.

For example, item dict(exclude_unset=True)。 Let’s look at our actual examples

from typing import List, Optional
from fastapi import FastAPI
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.2}
}
@app.put("/items/", response_model=Item)
def update_item(name: str, item: Item):
    stored_item_data = items[name]
    stored_item_model = Item(**stored_item_data)
    update_data = item.dict(exclude_unset=True)
    updated_item = stored_item_model.copy(update=update_data)
    items[name] = jsonable_encoder(updated_item)
    return updated_item
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: str):
    return items[item_id]

Let’s go and see the effect

 

 

Update partial data summary

In short, to update some data:

  • Use put or patch;

  • Extract stored data;

  • Put the data into pydantic model;

  • Generate a dict without the default value of the input model (use the exclude\u unset parameter);

    • Only the values set by the user are updated, and the stored values are not overwritten by the default values in the model.

  • Create a copy of the stored model and update its properties with the received data (using the update parameter).

  • Convert a copy of the model to a form that can be stored in the database (for example, using jsonable_encoder).

    • This approach is consistent with the pydantic model The dict () method is similar, but ensures that the value is converted to a data type that fits JSON, for example, datetime to str.

  • Save the data to the database;

  • Returns the updated model.

 

The article is first published in the official account. Welcome to pay attention.