def delete_category(category_id): try: # VALIDATE REQUEST HEADER, TOKEN token = validate_request_header(request, content=False, authorization=True) user = identity(token) # validate request's token # VALIDATE CATEGORY_ID category = CategoryModel.find_by_id(category_id) if category is None: return jsonify({'message': 'No category found'}), 404 # AUTHORIZE USER if user.id != category.author_id: return jsonify({'message': 'Unauthorized action'}), 401 # DELETE CATEGORY default_category = CategoryModel.find_by_name( current_app.config['DEFAULT_CATEGORY']) for item in category.items: item.category_id = default_category.id item.save_to_db() category.delete_from_db() # SUCCEED, RETURN MESSAGE return jsonify({'message': 'Category deleted'}), 200 except BadRequestError as err: return jsonify(err.represent()), 400 except UnauthorizedError as err: return jsonify(err.represent()), 401 except NotFoundError as err: return jsonify(err.represent()), 404
def update_category(category_id): try: # VALIDATE REQUEST HEADER, BODY, TOKEN token = validate_request_header(request, content=True, authorization=True) user = identity(token) # validate request's token validated_request_body = validate_request_body(request, action='update', resource_id=category_id, resource='category') # AUTHORIZE USER category = CategoryModel.find_by_id(category_id) if user.id != category.author_id: return jsonify({'message': 'Unauthorized action'}), 401 # UPDATE CATEGORY category.name = validated_request_body['name'] category.save_to_db() # SUCCEED, RETURN UPDATED CATEGORY return jsonify(category.represent()), 200 except BadRequestError as err: return jsonify(err.represent()), 400 except UnauthorizedError as err: return jsonify(err.represent()), 401 except NotFoundError as err: return jsonify(err.represent()), 404
def get_category(category_id): category = CategoryModel.find_by_id(category_id) # category found if category: return jsonify(category.represent()) # category not found return jsonify({'message': 'No category found'}), 404
def get(cls, category_id: int): category = CategoryModel.find_by_id(category_id) if category: return category_schema.dump(category), HttpStatusCode.OK.value return generate_message_json(HttpStatusCode.NOT_FOUND.value, CATEGORY_NOT_FOUND)
def patch(cls, category_id: int): json = request.get_json() # Check if the category exists category = CategoryModel.find_by_id(category_id) if not category: return generate_message_json(HttpStatusCode.NOT_FOUND.value, CATEGORY_NOT_FOUND) # Check if client is trying to edit readonly fields readonly = {"id", "user_id", "tasks"} keys = json.keys() forbidden = readonly & keys if forbidden: return generate_message_json( HttpStatusCode.BAD_REQUEST.value, FIELD_CANNOT_BE_EDITED.format(str(forbidden)[1:-1]), ) # Check if the client specified non existing attrs try: check_attr(json.keys(), category) for key, value in json.items(): setattr(category, key, value) category.save_to_db() return category_schema.dump(category), HttpStatusCode.OK.value except AttributeError as ae: return generate_message_json(HttpStatusCode.BAD_REQUEST.value, str(ae)) except SQLAlchemyError as se: return generate_message_json(HttpStatusCode.BAD_REQUEST.value, str(se))
def patch(self, id): # check if exists category = CategoryModel.find_by_id(id=id) if category is None: return { "message": "Category was not found", "success": False, "code": 404 }, 404 # fetch data data = request.get_json() # update fields category.title = data["title"] category.description = data["description"] #update to db try: category.update_to_db() except: return { "message": "There was an error please try again", "code": 500 }, 500 return { "message": "Category updated", "success": True, "code": 200, "result": category_schema.dump(category) }, 200
def delete(self, id): # check if exists category = CategoryModel.find_by_id(id=id) if category is None: return { "message": "Category was not found", "success": False, "code": 404 }, 404 # delete try: category.delete_from_db() except: return { "message": "There is an error, please try again", "success": False, "code": 500 }, 500 return { "message": "Category was deleted", "success": True, "code": 200, "result": category_schema.dump(category) }, 200
def get(self, _id): category = CategoryModel.find_by_id(_id) if category and current_identity.id != category.user_id: return {"message": "Not authorized to view this content"}, 401 if category: return category.json() return {"message": "Category was not found."}, 404
def post(self): _parser = reqparse.RequestParser() _parser.add_argument('categoryID', type=int, required=True, help="This field cannot be blank.") _parser.add_argument('name', type=str, required=True, help="This field cannot be blank.") _parser.add_argument('price', type=float, required=True, help="This field cannot be blank.") data = _parser.parse_args() category = CategoryModel.find_by_id(data['categoryID']) if not category: return {"message": "Category not found"}, 400 categoryType = CategoryTypeModel.find_by_categoryID_name( categoryID=data['categoryID'], name=data['name']) if categoryType: return { "message": "Category type with specified category and name already exists" }, 200 categoryType = CategoryTypeModel(name=data['name'], categoryID=data['categoryID'], price=float(data['price'])) categoryType.save_to_db() return { "message": "Category type saved", "categoryType": categoryType.json() }, 200
def get(self, category_id): category = CategoryModel.find_by_id(category_id) if category is None: return {"message": "Category not found."}, 404 return category.json(), 201
def get(self, id): email = get_jwt_identity() user = UserModel.find_by_email(email) category = CategoryModel.find_by_id(user.id, id) if category: return category_schema.dump(category).data return {"message": "Category not found"}, 404
def delete(self, _id): category = CategoryModel.find_by_id(_id) if category: category.delete_from_db() return { 'message': "Category id {} has been deleted".format(_id) }, 200 return {'message': "No Category id {} to delete".format(_id)}, 404
def json(self): category = CategoryModel.find_by_id(self.category_id) return { 'id': self.id, 'title': self.title, 'complete': self.complete, 'category_name': category.name }
def delete(self, id): email = get_jwt_identity() user = UserModel.find_by_email(email) category = CategoryModel.find_by_id(user.id, id) if category: category.delete_from_db() return {"message": "category deleted"}
def get(self, categoryID): category = CategoryModel.find_by_id(categoryID) if not category: return {"message": "Category not found"}, 400 categoryTypes = CategoryTypeModel.find_by_categoryID(categoryID) return { "categoryTypes": [categoryType.json() for categoryType in categoryTypes] }, 200
def delete(cls, category_id: int): category = CategoryModel.find_by_id(category_id) if category: # NOTE: Deletion will currently fail if the category contains any tasks category.delete_from_db() return "", HttpStatusCode.NO_CONTENT.value return generate_message_json(HttpStatusCode.NOT_FOUND.value, CATEGORY_NOT_FOUND)
def get(self, _id): category = CategoryModel.find_by_id(_id) if category: return category.json(), 200 # OK else: return { "message": "Category {} not found".format(_id) }, 404 #not found
def get(self, category_id: int): """ Obtener los datos de una categoría. """ category = CategoryModel.find_by_id(category_id) if not category: return { "message": f"La categoría con ID {category_id!r} no ha sido encontrada." }, 404 return category.json()
def delete(self, category_id): category = CategoryModel.find_by_id(category_id) if category is None: return {"message": "Category not found."}, 404 try: category.delete() except: return {"message": "An error occurred while deleting Category."}, 500 return {"message": "Category deleted."}, 200
def post(self): _parser = reqparse.RequestParser() _parser.add_argument('id', type=str, required=True, help="This field cannot be blank.") data = _parser.parse_args() category = CategoryModel.find_by_id(data["id"]) if not category: return {"message": "Category not found"}, 400 else: return {"category": category.json()}, 200
def delete(self): _category_parser = reqparse.RequestParser(bundle_errors=True) _category_parser.add_argument('id', type=non_empty_string, required=True, help="The id field is required!" ) data = _category_parser.parse_args() category = CategoryModel.find_by_id(data['id']) if category: category.delete_from_db() return {'message': 'Category Deleted'}
def get(self): _category_parser = reqparse.RequestParser() _category_parser.add_argument('id', type=non_empty_string, required=True, help="The id field is required!" ) data = _category_parser.parse_args() category = CategoryModel.find_by_id(data['id']) if category: return category.json() return {'message': 'Category not found'}, 404
def get(self, id): """GET request that deals with requests that look for a category by id""" # Request to the model Category = CategoryModel.find_by_id(id) # If the category exists if Category: # We return it as json return Category.json() # If not found return {'message': 'Category not found'}, 404
def delete(self): _parser = reqparse.RequestParser() _parser.add_argument('id', type=str, required=True, help="This field cannot be blank.") data = _parser.parse_args() category = CategoryModel.find_by_id(data["id"]) if len(category.categoryTypes) > 0: return { "message": "Category cannot be deleted as there are category types associated with it" } if category: category.delete_from_db() return {"message": "Category successfully deleted"}, 200
def put(self, args, _id): if CategoryModel.find_by_name(args['name']): return { "message": "Category name {} already exists".format(args['name']) }, 400 # category exists category = CategoryModel.find_by_id(_id) if category: category.name = args['name'] category.save_to_db() return { "message": "Category name {} has been updated".format(_id) }, 200 return { "message": "Category id {} doesn't exists".format(_id) }, 400 # media to update not found
def post(self, id): """POST request that deals with creation of a category provided an id""" # Call the model in order to find the category provided its id if CategoryModel.find_by_id(id): return {'message': "A Category with id '{}' already exists.".format(id)}, 400 # Push the data to the model Category = CategoryModel(id) try: # Try to save Category.save_to_db() except: # If error return {"message": "An error occurred creating the Category."}, 500 # once done we return the object as json return Category.json(), 201
def delete(self, category_id: int): """ Eliminar una categoría de la base de datos (Solo los admin pueden hacerlo). """ if current_identity.user_type != user_types['admin']: return { "message": "No tiene permitido eliminar una categoría." }, 401 category = CategoryModel.find_by_id(category_id) if not category: return {"message": "La categoría no ha sido encontrada."}, 404 category.delete_from_db() return { "message": f"Categoría con ID {category_id!r} eliminada correctamente." }
def delete(self, id): """DELETE request that deals with the deletion of a category with at a certain id""" # Call the model that fetch the category provided its id Category = CategoryModel.find_by_id(id) # if exists if Category: try: # we try to delete Category.delete_from_db() return {'message': 'Category deleted'} except: # if error during deletion return {'message': 'The category might belong to many books. To delete this catery you might want to delete all portfolio_book relations first, then portfolio, then all the books fo that category then finally delete the category.'} else: # if category not found return {'message' : 'Category not found'}, 404
def delete_category(user, category_id): # If the requested category doesn't exist then return 404 error. category = CategoryModel.find_by_id(category_id) if category is None: raise NotFoundError('No category found') # If user is not the creator of the category then returns unauthorized error. if user.id != category.author_id: raise UnauthorizedError('Unauthorized action') # Before the category is deleted, all items it contains is moved to default category. default_category = CategoryModel.find_by_name(current_app.config['DEFAULT_CATEGORY']) for item in category.items: item.category_id = default_category.id item.save_to_db() # If the action is valid, category is deleted. Succeed message is returned. category.delete_from_db() return jsonify({'message': 'Category deleted'})
def update_category(data, user, category_id): # If name is changed and new name exists then raises error. category = CategoryModel.find_by_name(data['name']) if category is not None and category.id != category_id: raise BadRequestError('category name already exists') # The resource that is requested has to exist. category = CategoryModel.find_by_id(category_id) if category is None: raise NotFoundError('No category found') # If user is not the creator of category then returns unauthorized error. if user.id != category.author_id: raise UnauthorizedError('Unauthorized action') # Request is valid. Category is updated, saved, and returned. category.update(data) category.save_to_db() return jsonify(dump_schema().dump(category).data)