示例#1
0
def get_items(category):
    """
    Get all items in a category
    :param: category's id
    :return: information about all items in that category. Raise a NotFoundError if cannot find the category
    """
    return jsonify(ItemSchema(many=True).dump(category.items))
示例#2
0
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)
示例#3
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)
    )
示例#4
0
def update_item(item, data, category, **_):
    """Update an existing item with new data.
    Note that only the one who owns the resource can update it.

    category_id is not needed as it was resolved by a decorator as category
    item_id is not needed as it was resolved by a decorator as item
    :param item: Item instance
    :param data: The new data of the item
    :param category: The category of this item
    :return:
    """

    # 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 and duplicated_item.id != item.id:
        raise DuplicatedItemError()

    # Proceed to update the item
    item.update(**data)
    item.save()

    return jsonify(
        ItemSchema().dump(item)
    )
示例#5
0
    def test_put_item_successfully(self, client):
        self._setup()
        response, json_response = put_item(client, item_id=self.items[0]["id"], data=self.put_item,
                                           access_token=self.access_token)

        assert response.status_code == 201, "Successful call should return 201 status code"
        assert ItemSchema().validate(json_response) == {}, "Validation should return empty error object"
示例#6
0
 def test_get_item_successfully(self, client):
     self._setup()
     item_id = self.items[0]["id"]
     response = client.get(f"/items/{item_id}")
     json_response = response.get_json()
     assert response.status_code == 200, "Successful call should return 200 status code"
     assert ItemSchema().validate(
         json_response) == {}, "Validation should return empty error object"
示例#7
0
def get_items():
    """
    :return: All items
    """
    items = Items.query.all()
    result = ItemSchema(many=True).dump(items)

    return jsonify(result.data)
    def test_get_category_items_successfully(self, client):
        self._setup()

        url = create_url_with_parameters(category_id=self.categories[0]["id"], limit=10, offset=0)
        response = client.get(url)
        json_response = response.get_json()
        assert response.status_code == 200, "Successful call should return 200 status code"
        assert ItemSchema(many=True).validate(json_response["items"]) == {}, "Validation should return empty error object"
示例#9
0
def get_item(item):
    """
    Get an item in a category
    :param: category's id, item's id
    :return:
    Information about the item.
    Raise a NotFoundError if cannot find item or category with that id
    """
    return jsonify(ItemSchema().dump(item))
示例#10
0
def get_category_items(category, pagination):
    try:
        items = ItemSchema(many=True).dump(
            category.items.limit(pagination["limit"]).offset(
                pagination["offset"]))
        total = category.items.count()
    except SQLAlchemyError as error:
        raise SQLAlchemyError(error)

    return jsonify({"items": items, "total": total}), 200
    def test_create_item_successfully(self, client):
        self._setup()
        response, json_response = create_item(client,
                                              access_token=self.access_token,
                                              category_id=self.category_id,
                                              data=self.new_item)

        assert response.status_code == 201, "Successful create item should return 201"
        assert ItemSchema().validate(
            json_response) == {}, "Validation should return empty error object"
示例#12
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
示例#13
0
def get_items_from_category(category_id):
    """
    :param category_id:
    :return: All items from a category which has id = category_id
    """
    if Categories.query.get(category_id) is None:
        return jsonify({'message': 'Category could not be found.'}), 404

    items = Items.query.filter_by(category_id=category_id).all()
    result = ItemSchema(many=True).dump(items)

    return jsonify(result.data)
示例#14
0
def update_item(user_id, data, item):
    if item.user_id != user_id:
        raise ForbiddenError("You are not allowed to edit this item.")

    try:
        item.name = data["name"]
        item.description = data["description"]
        item.category_id = data["category_id"]

        db.session.add(item)
        db.session.commit()
    except SQLAlchemyError as error:
        raise SQLAlchemyError(error)

    return jsonify(ItemSchema().dump(item)), 201
示例#15
0
def get_item_from_category(category_id, item_id):
    """
    :param category_id:
    :param item_id:
    :return: An item id=item_id from a category id=category_id
    """
    if Categories.query.get(category_id) is None:
        return jsonify({'message': 'Category could not be found.'}), 404
    if Items.query.get(item_id) is None:
        return jsonify({'message': 'Item could not be found.'}), 404

    item = Items.query.get(item_id)
    result = ItemSchema().dump(item)

    return jsonify(result.data)
示例#16
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
示例#17
0
def get_item(item, user, **_):
    """Get a specific item from a category given an ID.

    category_id is not needed as it was resolved by a decorator as category
    item_id is not needed as it was resolved by a decorator as item
    :param item: Item instance
    :param user: User instance of the authenticated user
    :return: Item information
    """

    # If authentication is provided,
    # update is_owner
    if user:
        item.is_owner = item.user_id == user.id

    return jsonify(
        ItemSchema().dump(item)
    )
示例#18
0
def update_item(user_id, data, item):
    """
    Update an item
    :param: category's id, user_id, item's id, new information about item
    :return:
    Information about updated item in json if succeed
    Raise a NotFoundError if cannot find item or category with that id
    Raise a ForbiddenError if not allowed to update this item
    """
    if item.user_id != user_id:
        raise ForbiddenError('Not allowed to modify this item.')

    item.name = data['name']
    item.description = data['description']
    db.session.add(item)
    db.session.commit()

    return jsonify(ItemSchema().dump(item))
示例#19
0
def get_items(category, user):
    """Get a list of items belong to a category.

    category_id is not needed as it was resolved by a decorator as category
    :param category: Category from which the item is being retrieved
    :param user: User instance of the authenticated user
    :return: A list of items with pagination information
    """

    # Validate pagination information
    try:
        pagination = RequestPaginationSchema().load(request.args)
    except ValidationError:
        raise InvalidPaginationFormatError

    # Get items with pagination
    items = category.items \
                    .order_by(ItemModel.created.desc()) \
                    .paginate(page=pagination.get('page'),
                              per_page=pagination.get('per_page'),
                              error_out=False)

    # In case the user get an out-of-range page
    if pagination.get('page') > items.pages > 0:
        raise ExceededRangePaginationError()

    # If authentication is provided,
    # update is_owner
    if user:
        for item in items.items:
            item.is_owner = item.user_id == user.id

    # Returns a payload with pagination
    return jsonify(ResponsePaginationSchema().load({
        'items': ItemSchema(many=True).dump(items.items),
        'total': items.total,
        'total_pages': items.pages,
        'page': items.page,
        'per_page': items.per_page
    }))
示例#20
0
def get_item(item):
    return jsonify(ItemSchema().dump(item)), 200
示例#21
0
    :return: An item id=item_id from a category id=category_id
    """
    if Categories.query.get(category_id) is None:
        return jsonify({'message': 'Category could not be found.'}), 404
    if Items.query.get(item_id) is None:
        return jsonify({'message': 'Item could not be found.'}), 404

    item = Items.query.get(item_id)
    result = ItemSchema().dump(item)

    return jsonify(result.data)


@app.route('/categories/<int:category_id>/items', methods=['POST'])
@auth_user
@validate_data(ItemSchema())
def create_item(data, user_id, category_id):
    """
    :param data:
    :param user_id:
    :param category_id:
    :return: Created an item to a category successful or fail
    """
    if Categories.query.get(category_id) is None:
        return jsonify({'message': 'Category could not be found.'}), 404

    title, description = data['title'], data['description']
    item = Items(title, description, category_id, user_id)
    item.save_to_db()
    db.session.commit()
示例#22
0
    # If authentication is provided,
    # update is_owner
    if user:
        item.is_owner = item.user_id == user.id

    return jsonify(
        ItemSchema().dump(item)
    )


# noinspection PyUnresolvedReferences
@app.route('/categories/<int:category_id>/items', methods=['POST'])
@require_authentication
@parse_category
@parse_with_schema(ItemSchema())
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()
示例#23
0
from flask import Blueprint, Response
from flask_jwt_extended import jwt_required, get_jwt_identity

from main.errors import NotFound, DuplicatedEntity, Forbidden, StatusCodeEnum
from main.models.category import CategoryModel
from main.models.item import ItemModel
from main.schemas.item import ItemSchema
from main.schemas.request import ItemPaginationQuerySchema
from main.schemas.response import create_pagination_response_schema
from main.utils.decorators.request_parser import request_parser
from main.utils.response_helpers import create_data_response

item_api = Blueprint('item', __name__)

item_schema = ItemSchema()
items_schema = ItemSchema(many=True)


@item_api.route('/items', methods=['GET'])
@request_parser(query_schema=ItemPaginationQuerySchema())
def get_items(query_params):
    """
    GET all items with pagination
    :param query_params:
    :queryparam page: page that client wants to get, default = 1
    :queryparam per_page: items per page that client wants to get, default = 5
    :queryparam category_id: Identifier or the category to which the items belong

    :raise ValidationError 400: When client passes invalid value for page, per_page
    :return: List of items, current_page, per_page, total.
    """