Updating models with SQLAlchemy
- Set metadata above
- Start writing!
- Create
startfolder - Create
endfolder - Create per-file diff between
endandstart(use "Compare Folders")
A frequent operation in REST APIs is the "upsert", or "update or insert".
This is an idempotent operation where we send the data we want the API to store. If the data identifier already exists, an update is done. If it doesn't, it is created.
This idempotency is frequently seen with PUT requests. You can see it in action here:
resources/item.py
@blp.arguments(ItemUpdateSchema)
@blp.response(200, ItemSchema)
def put(self, item_data, item_id):
item = ItemModel.query.get_or_404(item_id)
if item:
item.price = item_data["price"]
item.name = item_data["name"]
else:
item = ItemModel(**item_data)
db.session.add(item)
db.session.commit()
return item