from flask import request from sqlalchemy.exc import IntegrityError, NoResultFound from .blueprint import api_library from ....controller import LibraryController from ....schema.library.library import Library import logging logger = logging.getLogger(__name__) def update_library_item(library:Library, key, value): if key == "id": raise AttributeError("id is not updatable") try: library.__getattribute__(key) except AttributeError: raise AttributeError(f"{key} not in library") library.__setattr__(key, value) @api_library.route("/<_id>", methods=["PATCH"]) def update_library(_id): try: data:dict = request.json logger.debug(f"data: {data}") except Exception as e: logger.debug(f"{e}") return { "status": "error", "error": "JSON Required" }, 415 try: # TODO: function controller = LibraryController(_id) except NoResultFound as e: logger.debug({e}) return { "status": "error", "error": "Library not found" }, 404 library = controller.data for key, value in data.items(): try: update_library_item(library, key, value) except AttributeError as e: logger.debug(f"Error updating {e}") return { "status": "error", "error": e.name } try: controller.update() except IntegrityError as e: logger.debug(f"DB Error Creating {e}") return { "status": "error", "error": f"{e.orig}" }, 400 else: return { "status": "ok", "result": controller.data.to_dict() }, 200