Exemple #1
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))
def generate_items():
    items = [
        ItemModel(user_id=1,
                  category_id=1,
                  name="lamp",
                  description="This is a lamp, it emit light"),
        ItemModel(user_id=1,
                  category_id=3,
                  name="macbookpro",
                  description="Expensive shit"),
        ItemModel(user_id=1,
                  category_id=3,
                  name="dellxps15",
                  description="Less Expensive shit"),
        ItemModel(user_id=1,
                  category_id=3,
                  name="dellmonitor",
                  description="Good stuff"),
        ItemModel(user_id=2,
                  category_id=2,
                  name="toiletpaper",
                  description="We all need this"),
    ]
    with app.app_context():
        db.session.add_all(items)
        db.session.commit()
        return ItemSchema(many=True).dump(items)
Exemple #3
0
def create_item(data):
    item = ItemModel(
        name=data['name'],
        description=data.get('description', ""),
        category_id=data.get('category_id'),
        user_id=data['user_id']
    )
    ItemModel.save_to_db(item)
def create_item(title, description, cat_id):
    """
    Create user and save to database
    :param title: A unique string length >=4
    :param description: A string length >=4
    :param cat_id: category id
    :return: category object
    """
    item = ItemModel(title=title, description=description, category_id=cat_id)
    item.save()

    return item
Exemple #5
0
def create_item(user_id):
    data = request.get_json()
    validate = item_input_schema.load(data)
    if len(validate.errors) > 0:
        abort(400, {'errors': validate.errors})
    user = UserModel.query.get(user_id)
    category_id = validate.data.get('category_id')
    category = None
    if category_id is not None:
        category = CategoryModel.query.get(category_id)
        if category and category.user_id != user_id:
            return abort(403, {'message': 'unauthorized to assign item to category with id {}'
                         .format(category_id)})
    item = ItemModel(user=user, category=category, **data)
    item.save_to_db()
    return jsonify({'message': 'item with name {} has been successfully created'.format(data.get('name'))})
Exemple #6
0
def init_items():
    """
    Initiate item table
    """

    items = [
        {
            'name': 'Shawshank Redemption',
            'description': 'Starring Morgan Freeman.'
        },
        {
            'name': 'The Green Mile',
            'description': 'Starring Tom Hank'
        },
    ]
    user_id = 1
    category_id = 1

    for item in items:
        item_object = ItemModel(category_id=category_id,
                                user_id=user_id,
                                **item)
        db.session.add(item_object)

    db.session.commit()
def create_items(items):
    """
    Create items and save to database
    :param items: list of items (dict)
    """
    item_objs = [ItemModel(**item) for item in items]
    db.session.bulk_save_objects(item_objs)
    db.session.commit()
Exemple #8
0
def add_item(user_id, data, category):
    """
    Post a new item to a category
    :param: category's id, user's id, item's information
    :return: created item's information. Raise a NotFoundError if cannot find the category
    """
    item = ItemModel(category_id=category.id, user_id=user_id, **data)
    db.session.add(item)
    db.session.commit()

    return jsonify(ItemSchema().dump(item)), 201
Exemple #9
0
def create_item(data, user, category):
    """Create a new item in the given category.

    category_id is not needed as it was resolved by a decorator as category
    :param data: The data of the item
    :param user: User instance of the authenticated user
    :param category: Category from which the item is being created
    :return: A newly created Item
    """

    # Check if the category already has an item with the same name
    duplicated_item = category.items.filter_by(name=data.get('name')).one_or_none()

    if duplicated_item:
        raise DuplicatedItemError()

    # Proceed to create new item in category
    new_item = ItemModel(**data)
    new_item.user_id = user.id
    new_item.category_id = category.id

    # Save to DB
    new_item.save()

    return jsonify(
        ItemSchema().dump(new_item)
    )
Exemple #10
0
def get_item(item_id):
    """
    Get the item with id
    :param item_id: id of the category

    :raise Not Found 404: If item with that id doesn't exist
    :return: Item with that id
    """
    item = ItemModel.find_by_id(item_id)
    if item is None:
        raise NotFound(error_message='Item with this id doesn\'t exist.')

    return create_data_response(item_schema.dump(item))
Exemple #11
0
def create_item(user_id, category, data):
    item_name = data["name"]
    try:
        existing_item = ItemModel.query.filter_by(name=item_name).one_or_none()
    except SQLAlchemyError as error:
        raise SQLAlchemyError(error)
    if existing_item:
        raise BadRequestError(f"Item {item_name} already existed.")

    new_item = ItemModel(user_id=user_id, **data)
    try:
        db.session.add(new_item)
        db.session.commit()
    except SQLAlchemyError as error:
        raise SQLAlchemyError(error)

    return jsonify(ItemSchema().dump(new_item)), 201
Exemple #12
0
def delete_item(item_id):
    """
    Delete the item with id
    :param item_id: ID of the item we want to delete

    :raise Unauthorized 401: If not login
    :raise Forbidden 403: If user tries to delete other user's items
    :raise Not Found 404: If item with that id doesn't exist
    :return: 204 response
    """
    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 delete other users\'s item')
    item.delete()

    return Response(status=StatusCodeEnum.NO_CONTENT)
Exemple #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))