Exemplo n.º 1
0
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()
Exemplo n.º 2
0
    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
Exemplo n.º 3
0
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
Exemplo n.º 4
0
 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
Exemplo n.º 5
0
    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
Exemplo n.º 6
0
 def post(self):
     iKwargs = request.form.to_dict()
     categorys = CategoryModel.getAllData()
     names = [category['name'] for category in categorys]
     category = CategoryModel()
     if iKwargs['name'] in names:
         raise ModelRepeat(iKwargs['name'])
     data = {'name': iKwargs['name'], 'articleList': {}}
     category.create(data)
     return data
Exemplo n.º 7
0
    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
Exemplo n.º 8
0
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
Exemplo n.º 9
0
    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
Exemplo n.º 10
0
    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
Exemplo n.º 11
0
def add_category(db):
    categories = []
    for i in range(random.randint(1, 10)):
        category = CategoryModel(name=generate_username(),
                                 parent_id=random.randint(1, 2),
                                 depth=random.randint(1, 2),
                                 order=random.randint(1, 4))
        categories.append(category)

    db.session.bulk_save_objects(categories)
    db.session.commit()
Exemplo n.º 12
0
    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
Exemplo n.º 13
0
    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()}
Exemplo n.º 14
0
    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
Exemplo n.º 15
0
    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
Exemplo n.º 16
0
    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
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
    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
Exemplo n.º 19
0
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
Exemplo n.º 20
0
    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
Exemplo n.º 21
0
    def post(self):
        data = Category.parser.parse_args()
        if CategoryModel.find_by_name(data['name']):
            return {
                'message':
                "A category with name '{}' already exists.".format(
                    data['name'])
            }, 400

        category = CategoryModel(uuid.uuid4().hex, data['name'])
        try:
            category.save_entity()
        except:
            return {
                'message': "An error occurred while creating the category."
            }, 500

        return category.json(), 201
Exemplo n.º 22
0
    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
Exemplo n.º 23
0
    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
Exemplo n.º 24
0
    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
Exemplo n.º 25
0
    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
Exemplo n.º 26
0
    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
Exemplo n.º 27
0
    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
Exemplo n.º 28
0
    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
Exemplo n.º 29
0
    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()
Exemplo n.º 30
0
    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