Esempio n. 1
0
def update_item(item_id, user_info):
    """
    Update an item, find by its id
    Protected
    :param item_id: item id
    :param user_info: decoded access token
    :return:
    """

    data = request.get_json()

    # Validate json
    schema = ItemSchema(dump_only=('slug', 'id'))
    errors = schema.validate(data)
    if len(errors) > 0:
        raise ValidationError('Post data error', errors)

    # Validate item id
    item = ItemModel.get_user_item(item_id, user_info.get('id'))
    if item is None:
        raise ValidationError('Item not found!')

    # Validate item name
    slug = slugify(data['name'])
    if slug != item.slug:
        valid = ItemModel.validate_slug(slug)

        if not valid:
            raise ValidationError('An item with the same name has already been added. Please try another name.')

    # Validate category id
    category = CategoryModel.find(category_id=data['category_id'])
    if category is None:
        raise ValidationError('Invalid category Id')

    item.name = data['name']
    item.description = data['description']
    item.category_id = data['category_id']
    item.slug = slugify(item.name)

    db.session.add(item)
    db.session.commit()

    item_schema = ItemSchema()
    result = item_schema.dump(item)

    return send_success(result.data)
Esempio n. 2
0
def create_item(user_info):
    """
    Add an item
    Protected
    :param user_info: decoded access token
    :return:
    """

    data = request.get_json()

    # Validate json
    schema = ItemSchema(dump_only=('slug', 'id'))
    errors = schema.validate(data)
    if len(errors) > 0:
        raise ValidationError('Post data error', errors)

    # Validate item name
    valid = ItemModel.validate_slug(slugify(data['name']))

    if not valid:
        raise ValidationError('An item with the same name has already been added. Please try another name.')

    # Validate category id
    category = CategoryModel.find(category_id=data['category_id'])

    if category is None:
        raise ValidationError('Invalid category Id')

    item = ItemModel(name=data['name'], description=data['description'], category_id=data['category_id'],
                     user_id=user_info['id'], slug=slugify(data['name']))

    db.session.add(item)
    db.session.commit()

    item_schema = ItemSchema()
    result = item_schema.dump(item)

    return send_success(result.data)