Ejemplo n.º 1
0
def create_category(data):
    category = CategoryModel(
        name=data['name'],
        description=data.get('description', None),
        user_id=data['user_id'],
    )
    CategoryModel.save_to_db(category)
Ejemplo n.º 2
0
def generate_categories():
    categories = [
        CategoryModel(name="household"),
        CategoryModel(name="groceries"),
        CategoryModel(name="tech")
    ]
    with app.app_context():
        db.session.add_all(categories)
        db.session.commit()
        return CategorySchema(many=True).dump(categories)
Ejemplo n.º 3
0
def create_category(title, description):
    """
    Create category and save to database
    :param title: A unique string length >=4
    :param description: A string length >=4
    :return: category object
    """
    category = CategoryModel(title=title, description=description)
    category.save()

    return category
Ejemplo n.º 4
0
def create_category(user_id):
    data = request.get_json()
    user = UserModel.query.get(user_id)
    validate = category_input_schema.load(data)
    if len(validate.errors) > 0:
        abort(400, {'errors': validate.errors})
    category = CategoryModel(user=user, **validate.data)
    category.save_to_db()
    return jsonify({
        'message':
        'category with name {} has been successfully created'.format(
            validate.data.get('name'))
    })
Ejemplo n.º 5
0
def create_item(body_params):
    """
    Create an item
    :param body_params:
    :bodyparam title: Title of the item
    :bodyparam description: Description of the item
    :bodyparam category_id: Identifier of the category to which this item will belong

    :raise ValidationError 400: if form is messed up
    :raise DuplicatedEntity 400: If try to create an existed object.
    :raise BadRequest 400: if the body mimetype is not JSON
    :raise Unauthorized 401: If not login
    :raise NotFound 404: If category_id is not valid
    :return: the created item
    """
    if CategoryModel.find_by_id(body_params['category_id']) is None:
        raise NotFound(error_message='Category with this id doesn\'t exist.')
    if ItemModel.query.filter_by(title=body_params['title']).first():
        raise DuplicatedEntity(error_message='Item with this title exists.')

    body_params['creator_id'] = get_jwt_identity()
    item = ItemModel(**body_params)
    item.save()

    return create_data_response(item_schema.dump(item))
Ejemplo n.º 6
0
def delete_category(category_id):
    """
    Delete the category with id
    :param category_id: ID of the category we want to delete

    :raise Unauthorized 401: If user is not login-ed
    :raise Forbidden 403: if user try to update other user's category
    :raise Not Found 404: If category with that id doesn't exist
    :return: 204 response
    """
    category = CategoryModel.find_by_id(category_id)
    if category is None:
        raise NotFound(error_message='Category with this id doesn\'t exist.')

    creator_id = get_jwt_identity()
    if creator_id != category.creator_id:
        raise Forbidden(
            error_message='You can\'t delete other users\'s category')

    db.session.query(ItemModel).filter(
        ItemModel.category_id ==
        category_id).delete()  # delete all items in this category
    category.delete()

    return Response(status=StatusCodeEnum.NO_CONTENT)
Ejemplo n.º 7
0
def create_categories(categories):
    """
    Create user and save to database
    :param categories: list of categories (dict)
    """
    category_objs = [CategoryModel(**cat) for cat in categories]
    db.session.bulk_save_objects(category_objs)
    db.session.commit()
Ejemplo n.º 8
0
def create_category(body_params):
    """
    Create a category
    :param body_params:
    :bodyparam title: Title of the category
    :bodyparam description: Description of the category

    :raise ValidationError 400: if form is messed up
    :raise DuplicatedEntity 400: If try to create an existed object
    :raise BadRequest 400: if the body mimetype is not JSON
    :raise Unauthorized 401: If user is not login-ed
    :return: the created category
    """
    if CategoryModel.query.filter_by(title=body_params['title']).first():
        raise DuplicatedEntity(
            error_message='Category with this title has already existed.')

    body_params['creator_id'] = get_jwt_identity()
    category = CategoryModel(**body_params)
    category.save()

    return create_data_response(category_schema.dump(category))
Ejemplo n.º 9
0
def get_category(category_id):
    """
    Get the category by id
    :param category_id: id of the category want to get

    :raise Not Found 404: If category with that id doesn't exist
    :return: Category with that id
    """
    category = CategoryModel.find_by_id(category_id)
    if category is None:
        raise NotFound(error_message='Category with this id doesn\'t exist.')

    return create_data_response(category_schema.dump(category))
Ejemplo n.º 10
0
def add_category(data):
    """
    Post a new category
    :param: category's name and description
    :return: created category's name and description in json
    Raise a BadRequestError if that name already exists
    """
    if CategoryModel.query.filter_by(name=data['name']).one_or_none():
        raise BadRequestError('A Category with that name already exists.')

    category = CategoryModel(**data)
    db.session.add(category)
    db.session.commit()

    return jsonify(CategorySchema().dump(category)), 201
Ejemplo n.º 11
0
def create_category(user_id, data):
    category_name = data["name"]
    try:
        existing_category = CategoryModel.query.filter_by(
            name=category_name).one_or_none()
    except SQLAlchemyError as error:
        raise SQLAlchemyError(error)
    if existing_category:
        raise BadRequestError(f"Category {category_name} already existed.")
    # create new category
    new_category = CategoryModel(name=category_name)
    try:
        db.session.add(new_category)
        db.session.commit()
    except SQLAlchemyError as error:
        raise SQLAlchemyError(error)

    return jsonify(CategorySchema().dump(new_category)), 201
Ejemplo n.º 12
0
def init_categories():
    """
    Initiate category table
    """

    categories = [{
        'name': 'Films',
        'description': 'Before 2000s'
    }, {
        'name': 'Songs',
        'description': 'Rock, Pop, Soul'
    }, {
        'name': 'Food',
        'description': 'European food'
    }]
    for category in categories:
        category_object = CategoryModel(**category)
        db.session.add(category_object)

    db.session.commit()
Ejemplo n.º 13
0
def update_item(item_id, body_params):
    """
    Update the item with id
    :param item_id: ID of the item we want to update
    :param body_params:
    :bodyparam title: Title of the item
    :bodyparam description: Description of the item

    :raise ValidationError 400: if form is messed up
    :raise DuplicatedEntity 400: if there is a item with the title.
    :raise BadRequest 400: if the body mimetype is not JSON
    :raise Unauthorized 401: If not login
    :raise Forbidden 403: If user tries to delete other user's items
    :raise NotFound 404: If category_id is not valid or item with id is not valid
    :return: the updated item
    """
    category_id = body_params.get('category_id')
    # After SchemaValidation, category_id is either None or a number, None will pass through this test
    if category_id and CategoryModel.find_by_id(category_id) is None:
        raise NotFound(error_message='Category with this id doesn\'t exist.')

    item = ItemModel.find_by_id(item_id)
    if item is None:
        raise NotFound(error_message='Item with this id doesn\'t exist.')
    if item.creator_id != get_jwt_identity():
        raise Forbidden(error_message='You can\'t update other users\'s item')

    title = body_params.get('title')
    description = body_params.get('description')
    if title:
        if ItemModel.query.filter_by(title=title).first():
            raise DuplicatedEntity(error_message='Item with this title has already existed.')
        item.title = title
    if description:
        item.description = description
    if category_id:
        item.category_id = category_id
    item.save()

    return create_data_response(item_schema.dump(item))
Ejemplo n.º 14
0
def update_category(category_id, body_params):
    """
    Update the category with id
    :param category_id: ID of the category we want to update
    :param body_params:
    :bodyparam title: Title of the category
    :bodyparam description: Description of the category

    :raise ValidationError 400: if form is messed up
    :raise DuplicatedEntity 400: if there is a category with the title
    :raise BadRequest 400: if the body mimetype is not JSON
    :raise Unauthorized 401: If user is not login-ed
    :raise Forbidden 403: if user try to update other user's category
    :raise Not Found 404: If category with that id doesn't exist
    :return: the updated category
    """
    category = CategoryModel.find_by_id(category_id)
    if category is None:
        raise NotFound(error_message='Category with this id doesn\'t exist.')

    creator_id = get_jwt_identity()
    if creator_id != category.creator_id:
        raise Forbidden(
            error_message='You can\'t update other users\'s category')

    title = body_params.get('title')
    description = body_params.get('description')
    if title:
        if CategoryModel.query.filter_by(title=title).first():
            raise DuplicatedEntity(
                error_message='There is already a category with this title.')
        category.title = title
    if description:
        category.description = description
    category.save()

    return create_data_response(category_schema.dump(category))