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 put(self, name): data = Category.parser.parse_args() if len(name) > Configuration.MAX_CATEGORY_NAME_SIZE: return { 'message': 'A name\'s length is more than {}'.format( Configuration.MAX_CATEGORY_NAME_SIZE) } posts_id = data['posts'] if posts_id: posts = get_posts(posts_id) else: posts = [] category = CM.find_by_name(name) if not category: category = CM(name=name) else: category.name = name category.posts = [] 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): data = request.get_json() category = CategoryModel(label=data["label"], value=data["value"]) try: category.save_to_db() return {"message": "OK"}, 200 except: return {"message": "error"}, 400
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 post(self, name): if CategoryModel.find_by_name(name): return {'message': 'Category already exists'}, 400 category = CategoryModel(name) try: category.save_to_db() except Exception: return {'message': 'Error occured while creating category'}, 500 return category.json(), 201
def create_category(data, user): # If category's name is not unique then raises error. category = CategoryModel.find_by_name(data['name']) if category is not None: raise BadRequestError('category already exists') # Request is valid then new category is created, saved, and returned. data['author_id'] = user.id category = CategoryModel(**data) category.save_to_db() return jsonify(dump_schema().dump(category).data), 201
def post(self): data = _category_parser.parse_args() category = CategoryModel(**data) try: category.save_to_db() except: return {"message": "An error occurred creating the category"}, 500 return category.json(), 201
def post(self, name): if CategoryModel.find_by_name(name): return {'message': "A category with name '{}' already exists.".format(name)}, 400 category = CategoryModel(name) try: category.save_to_db() except: return {"message": "An error occurred creating the category."}, 500 return category.json(), 201
def post(self): email = get_jwt_identity() current_user = UserModel.find_by_email(email) data = Category.parser.parse_args() data['user_id'] = current_user.id total_per_category = (data['percentage'] / 100) * current_user.salary data['total'] = total_per_category data['remaining'] = total_per_category # data['remaining'] = total_per_category - sum = db.session.query(func.sum(CategoryModel.percentage)).filter( CategoryModel.user_id == current_user.id).scalar() # number_of_tags = db.session.query(func.count(StoreModel.id)).scalar() print(sum) if sum == None and data['percentage'] <= 100: category = CategoryModel(**data) elif sum != None and data[ 'percentage'] + sum <= 100 and not db.session.query( CategoryModel.tags).filter( CategoryModel.tags == data['tags'], CategoryModel.user_id == current_user.id).all(): category = CategoryModel(**data) else: if not (sum != None and data['percentage'] + sum <= 100): return { 'message': "total percentage can't be more than 100%" }, 400 elif db.session.query(CategoryModel.tags).filter( CategoryModel.tags == data['tags'], CategoryModel.user_id == current_user.id).all(): return { 'message': "you have already used this {} tag. One tag can be used only once but can be edited" .format(data['tags']) }, 403 else: return { 'message': "You are not allowed to add more than 3 tags" }, 400 try: category.save_to_db() except: return { 'message': "An error occurred while inserting an item" }, 500 # internal server error return category_schema.dump(category).data, 201
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, name): category = CategoryModel.find_by_name(name) if category: return { "message": f"A category with name {name} already exists" }, 400 category = CategoryModel(name) try: category.save_to_db() except: return {"message": "An error occured while creating category"}, 500 return category.json(), 201
def post(cls, name): category = CategoryModel.find_existing_by_name(name) if category: return {"message": "Category with name '{}' already exists".format(name)}, 400 data = cls.parser.parse_args() category = CategoryModel(name, **data) try: category.save_to_db() except IntegrityError as e: return {"database_exception": str(e)}, 400 except: return {"message": "Internal error occurred during insertion."}, 500 return category.json(), 201
def put(self, category_name): data = Category.parser.parse_args() category = CategoryModel.find_by_name(category_name) if category is None: category = CategoryModel(category_name, data['category_value']) else: category.category_value = data['category_value'] try: category.save_to_db() except: return {"message": " unable to save /update category in DB"}, 500 return category.json(), 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 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
def post(self): _category_parser = reqparse.RequestParser(bundle_errors=True) _category_parser.add_argument('name', type=non_empty_string, required=True, help="The name field is required!" ) data = _category_parser.parse_args() if CategoryModel.find_by_name(data['name']): return {'message': "A category with name {} already exists".format(data['name'])}, 400 article = CategoryModel(**data) try: article.save_to_db() except Exception as e: return {'message': 'An error occurred while creating the category.'}, 500 return article.json(), 201
def post(self, name): if CategoryModel.find_by_name(name): return { 'message': "A category with the name of '{}' already exists".format(name) } category = CategoryModel(name) try: category.save_to_db() except: return { 'message': "An error occured while creating the category." }, 500 return {'message': "Category '{}' was created".format(name)}, 201
def put(cls, name): category = CategoryModel.find_existing_by_name(name) data = cls.parser.parse_args() if not category: category = CategoryModel(name, **data) else: category.update(data) try: category.save_to_db() except IntegrityError as e: return {"database_exception": str(e)}, 400 except: return {"message": "Internal error occurred during the update."}, 500 return category.json(), 201
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 post(self): data = CreateCategory.parser.parse_args() if CategoryModel.find_by_name(data['name']): return { 'message': "An category with name '{}' already exists.".format( data['name']) }, 400 category = CategoryModel(**data) try: category.save_to_db() except: return { "message": "An error occurred inserting the category." }, 500 return category.json(), 201
def post(self): """ Agregar una nueva categoría (Solo los admin pueden hacerlo). """ if current_identity.user_type != user_types['admin']: return { "message": "No tiene permitido crear nuevas categorías." }, 401 data = CategoryList.parser.parse_args() if CategoryModel.find_by_name(data['name']): return { "message": f"La categoría {data['name']!r} ya existe." }, 400 new_category = CategoryModel(**data) new_category.save_to_db() return new_category.json(), 201
def post(self, name): """POST request that deals with creation of a category provided a name""" # Call the model to look for a category provided a name if CategoryModel.find_by_name(name): return {'message': "A Category with name '{}' already exists.".format(name)}, 400 # We create the category with the given name Category = CategoryModel(name) try: # try to save and commit Category.save_to_db() except: # if error during saving and committing return {"message": "An error occurred creating the Category."}, 500 # we return the json of the category return Category.json(), 201
def post(self, name): if CategoryModel.find_by_name(name): return { 'success': False, 'message': 'A category with this name already exists' }, 400 category = CategoryModel(None, name) # try to save try: category.save_to_db() except: return {'success': False, 'message': 'Something went wrong'}, 500 return { 'success': True, 'message': 'A category was successfully created' }, 201
def put(self, id): data = EditCategory.parser.parse_args() ex_category = CategoryModel.find_by_name(data['name']) if ex_category and ex_category.id != id: return { 'message': "An category with name '{}' already exists.".format( data['name']) }, 400 category = CategoryModel.find_by_id(id) if category: category.name = data['name'] else: category = CategoryModel(**data) category.save_to_db() return category.json()
def post(self, category_name): category = CategoryModel.find_by_name(category_name) if category: return { 'message': " category {} already exists".format(category_name) }, 400 data = Category.parser.parse_args() category = CategoryModel(category_name, data['category_value']) try: category.save_to_db() # passing product object to insert # print(category) except: return { "message": "error occured while loading category data into DB " }, 400 return category.json(), 201
def put(self, category_id): _category_parser = reqparse.RequestParser(bundle_errors=True) _category_parser.add_argument('name', type=non_empty_string, required=False, help="The name field is required!" ) data = _category_parser.parse_args() category = CategoryModel.find_by_id(category_id) if category is None: category = CategoryModel(**data) else: category.name = data['name'] if data['name'] is not None else category.name try: category.save_to_db() except Exception as e: return {'message': 'An error occurred while creating the category.'}, 500 return category.json(), 201
def post(**token): """Handle the request of creating a new item If the new item has a new category we create that category too. Arguments: Token: dictionary format {"identity": user id, "iat": the time the token was created} Return: Item if success: JSON format { "id":int, "name": str, "price":float, "category_id":int, "user_id":int } Status code: int 201 if OK """ user_id = token["identity"] # Validate information on the request body data = validate_item_input(request.json, ItemSchema) # Create a new category if necessary for the new 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 # Create the item item = ItemModel(**data, user_id=user_id) item.save_to_db() return item_schema.dump(item), 201
def put(self): data = Category.parser.parse_args() data = { "name": data['name'].lower(), "type": data['type'].lower(), "budget": data['budget'] } category = CategoryModel.find_by_name(data['name'].lower()) if category is None: category = CategoryModel(**data) else: if data['budget'] is not None: category.budget = data['budget'] if not category.type == data['type']: category.type = data['type'] TransactionModel.update_prices(**data) category.save_to_db() return category.json()
def post(self): _parser = reqparse.RequestParser() _parser.add_argument('name', type=str, required=True, help="This field cannot be blank.") _parser.add_argument('urgency', type=int, required=True, help="This field cannot be blank.") data = _parser.parse_args() category = CategoryModel.find_by_name(data['name']) if category: return {"message": "Category with name already exists"}, 400 category = CategoryModel(name=data['name'], urgency=data['urgency']) category.save_to_db() return { "message": "Category created successfully", "category": category.json() }, 201
def post(self): data = Category.parser.parse_args() name = data['name'] category = CategoryModel.find_by_name(name) if category: return { "message": "That category, {}, already exists.".format(name) }, 400 category = CategoryModel(name, current_identity.id) try: category.save_to_db() except: return { "message": "An error occured while creating the category." }, 500 return category.json(), 201