def post(self): data = PayProducts.parser.parse_args() try: for payed_product in data.get('products'): sold_product = SoldProductModel.find_by_id( payed_product.id['id']) sold_product.payment_pending = False sold_product.update_to_db() except: return { "message": "an error occurred while updating the sales" }, 500 category = CategoryModel.find_by_name('pago_provedor') if not category: category = CategoryModel.create_category('pago_provedor') transaction = TransactionModel(transaction_id=None, amount=data.get('total'), date=str(data.get('date'))[:19], description=data.get('description'), is_expense=True, currency_id=data.get('currency_id'), category_id=category.category_id, method=data.get('method'), exchange=data.get('exchange')) transaction.save_to_db() return transaction.json(), 201
def seed_all(): db.create_all() # Categories sport = CategoryModel(name="Sport") politics = CategoryModel(name="Politics") db.session.add(sport) db.session.add(politics) db.session.commit() # Posts post1 = PostModel(title="Some post about sport") post1.category = sport post2 = PostModel(title="Politics sucks etc") post2.category = politics db.session.add(post1) db.session.add(post2) db.session.commit() # Tags tag1 = TagModel(name="Trump") tag2 = TagModel(name="Real Madrid") tag3 = TagModel(name="Champtions League") tag4 = TagModel(name="World Affairs") db.session.add(tag1) db.session.add(tag2) db.session.add(tag3) db.session.add(tag4) db.session.commit()
def create_category(): try: # VALIDATE REQUEST'S HEADERS, TOKEN, BODY token = validate_request_header(request, content=True, authorization=True) user = identity(token) # validate request's token validated_request_body = validate_request_body(request, action='create', resource='category') # CREATE CATEGORY category = CategoryModel(name=validated_request_body['name'], author_id=user.id) category.save_to_db() # SUCCEED, RETURN CREATED CATEGORY return jsonify(category.represent()), 201 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 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 get(cls, role: str): # role_json = request.get_json() # role = role_json["role"] print(role) try: if role == USER_ROLES["worker"]: data = inventory_worker_schema.dump(InventoryModel.get_worker_inventory()) editable = {} return {"data": data, "editable": editable}, 200 if role == USER_ROLES["supervisor"]: data = inventory_supervisor_schema.dump(InventoryModel.get_supervisor_inventory()) editable = { "category": category_schema.dump(CategoryModel.get_all()) } return {"data": data, "editable": editable}, 200 if role == USER_ROLES["statistics"]: data = inventory_statistics_schema.dump(InventoryModel.get_all()) categories = category_schema.dump(CategoryModel.get_all()) status = INVENTORY_STATUS return { "data": data, "editable": { "category": categories, "inventoryStatus": status } }, 200 except: return {"message": "error"}, 400
def post(self, name): if name: if CM.find_by_name(name): return { 'message': 'A category with name \'{}\' already exists'.format(name) }, 400 if len(name) > Configuration.MAX_CATEGORY_NAME_SIZE: return { 'message': 'A title\'s length is more than {}'.format( Configuration.MAX_CATEGORY_NAME_SIZE) } data = Category.parser.parse_args() posts_id = data['posts'] if posts_id: posts = get_posts(posts_id) else: posts = [] category = CM(name=name) if posts: category = add_posts(category, posts) try: category.save_to_db() except SQLAlchemyError as e: err = str(e.__class__.__name__) return {'message': '{}'.format(err)}, 500 return category.get_json(), 201
def post(cls): # POST /category data = cls.parser.parse_args() category = CategoryModel(**data) try: category.save_to_db() except: return {"Messege": "An error occured inserting the category."}, 500 return category.json(), 201
def put(self): data = _category_parser.parse_args() category = CategoryModel(**data) try: category.update_to_db() except: return {"message": "An error occurred updating the category"}, 500 return category.json(), 200
def post(self): data = self.parser.parse_args() new_cat = CategoryModel(**data) try: db.session.add(new_cat) db.session.commit() except exc.IntegrityError as e: return {"message": e.args[0]}, 500 except: return {"message": "Something went wrong"}, 500 return {'data': new_cat.json()}
def post(self): data = Category.parse.parse_args() category = CategoryModel.find_by_cat_name(data['cat_name']) if category: return { "CategoryAlreadyExistsError": { "message": "Category with given name already exists" } }, 400 category = CategoryModel(data['cat_name']) category.save_to_db() return {"message": "Category Create Successfully"}, 200
def post(self): data = parser.parse_args() if CategoryModel.query.filter_by(name=data['name']).first(): msg = "A category with name:'{}' already exists.".format( data['name']) return {"message": msg}, 400 category = CategoryModel(**data) try: category.save() except: return {"message": "An error occurred while inserting Category"}, 500 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 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): claims = get_jwt_claims() if not claims['active']: return { 'message': 'Error # 34 in Product Resource, You have not been activated by the admin' }, 400 current_user = UserModel.find_by_user(get_jwt_identity()) if not claims['is_superuser']: approved_zid_list = VbusinessModel.find_all_business_list() business_Id_list = [current_user.businessId] if current_user.businessId not in approved_zid_list: return { 'message': 'Error # 182 in Customer Resource, You have not been authorized to use this business' }, 400 else: business_Id_list = VbusinessModel.find_all_business_list() category_list = CategoryModel.find_all_category_list() all_items = [ item.json() for item in CaitemModel.find_by_zid_category( business_Id_list, category_list) ] product_count = len(all_items) return {'rowcount': product_count}, 200
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(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 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 __init__(self, desc, ecoPoints, savings, weekly, category): self.desc = desc self.ecoPoints = ecoPoints self.savings = savings self.weekly = weekly self.category_id = getattr( CategoryModel.find_existing_by_name(category), "id", None)
def get(self, id): category = CategoryModel.find_by_cat_name(id) if category: return category.json() return { "CategoryNotFound": {"Category with given name already exists"} }, 400
def __init__(self, name, desc, goal, below, category): self.name = name self.desc = desc self.goal = goal self.below = below self.category_id = getattr( CategoryModel.find_existing_by_name(category), "id", None)
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 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 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 post(self, args): if CategoryModel.find_by_name(**args): return { "message": "A category named {} already exists".format(args['name']) }, 400 # Bad request category = CategoryModel(**args) # creator = CreatorModel(data['username'], data['password']) # for each of the keys in data say key = value # ie username = value, password = value category.save_to_db() return { "message": "Category {} created successfully".format(args['name']) }, 201 # created
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 put(id, **token): """Handles the request of updating an item from its owner If the item has a new category we create that category too. Arguments: id: int the index of the item user want to update Token: dictionary format {"identity": user id, "iat": the time the token was created} Return: Message if success: dictionary format {"msg": "Item updated!"} Message if error: dictionary format {"msg": The error message} Status code: int 200 if OK 403 if user is not the owner 404 if item not found """ # Get the id of the request sender from JWT user_identity = token["identity"] item = ItemModel.find_by_id(id) # Validate information on the request body data = validate_item_input(request.json, ItemSchema) # Only update an existing item if item: if item.user_id != user_identity: return {"msg": "You need to be the owner!"}, 403 # Create a new category if necessary for the item category = CategoryModel.find_by_name(data["category"]["name"]) if not category: category = CategoryModel(data["category"]["name"]) category.save_to_db() data["category"] = category.id item.update_to_db(**data) else: return {"msg": "Item not found!"}, 404 return {"msg": "Item updated!"}, 200