|
| 1 | +import uuid |
| 2 | +from flask.views import MethodView |
| 3 | +from flask_smorest import Blueprint, abort |
| 4 | + |
| 5 | +from schemas import ItemSchema, ItemUpdateSchema |
| 6 | +from db import items |
| 7 | + |
| 8 | +blp = Blueprint("Items", "items", description="Operations on items") |
| 9 | + |
| 10 | + |
| 11 | +@blp.route("/item/<string:item_id>") |
| 12 | +class Item(MethodView): |
| 13 | + @blp.response(200, ItemSchema) |
| 14 | + def get(self, item_id): |
| 15 | + try: |
| 16 | + return items[item_id] |
| 17 | + except KeyError: |
| 18 | + abort(404, message="Item not found.") |
| 19 | + |
| 20 | + def delete(self, item_id): |
| 21 | + try: |
| 22 | + del items[item_id] |
| 23 | + return {"message": "Item deleted."} |
| 24 | + except KeyError: |
| 25 | + abort(404, message="Item not found.") |
| 26 | + |
| 27 | + @blp.arguments(ItemUpdateSchema) |
| 28 | + @blp.response(200, ItemSchema) |
| 29 | + def put(self, item_data, item_id): |
| 30 | + try: |
| 31 | + item = items[item_id] |
| 32 | + |
| 33 | + # https://blog.teclado.com/python-dictionary-merge-update-operators/ |
| 34 | + item |= item_data |
| 35 | + |
| 36 | + return item |
| 37 | + except KeyError: |
| 38 | + abort(404, message="Item not found.") |
| 39 | + |
| 40 | + |
| 41 | +@blp.route("/items") |
| 42 | +class ItemList(MethodView): |
| 43 | + @blp.response(200, ItemSchema(many=True)) |
| 44 | + def get(self): |
| 45 | + return items.values() |
| 46 | + |
| 47 | + @blp.arguments(ItemSchema) |
| 48 | + @blp.response(201, ItemSchema) |
| 49 | + def post(self, item_data): |
| 50 | + for item in items.values(): |
| 51 | + if ( |
| 52 | + item_data["name"] == item["name"] |
| 53 | + and item_data["store_id"] == item["store_id"] |
| 54 | + ): |
| 55 | + abort(400, message=f"Item already exists.") |
| 56 | + |
| 57 | + item_id = uuid.uuid4().hex |
| 58 | + item = {**item_data, "id": item_id} |
| 59 | + items[item_id] = item |
| 60 | + |
| 61 | + return item |
0 commit comments