def similar_get(id, body):
    """Returns the set of items ordered by similarity, compared to the given query item
    :param id: 
    :type id: str
    :param body: 
    :type body: dict | bytes
    :rtype: ResultItemSet
    """
    try:
        vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english')
        if connexion.request.is_json:
            data = {}
            input_item = Item(id=id, name='', similarity=0)
            results = []
            item_set = ItemSet.from_dict(connexion.request.get_json())
            for i in item_set.data:
                if i.id != id:
                    data[i.id] = i.name
                else:
                    input_item.name = i.name
            for item in data:
                results.append(
                    (Item(id=item, name=data[item], similarity=cosine_sim(input_item.name, data[item], vectorizer))))
            item_set.data = sorted(results, key=lambda it: (it.similarity), reverse=True)
    except Exception as e:
        logger.warning(e, connexion.request)

    return item_set
示例#2
0
 def new_item(self, item_name, description, date=datetime.datetime.utcnow()):
     """method used for creating a  bucket list"""
     item = Item(item_name=item_name,
                 description=description,
                 owner_id=self._id,
                 date=date)
     item.save_to_items()
示例#3
0
def update_item(shopping_list_name, name, price, quantity, category):
    form = AddItem()
    """ 
    Item that we wish to update is created from parameters passed in the URL 
    """
    item_to_update = Item(name=name,
                          price=price,
                          category=category,
                          quantity=quantity)

    if form.validate_on_submit():
        item = Item(name=form.item_name.data,
                    price=form.item_price.data,
                    quantity=form.item_quantity.data,
                    category=form.category.data)

        try:
            shopping_list = current_user.get_shopping_lst(shopping_list_name)
            shopping_list.update_item(new_item=item, old_item=item_to_update)
            flash(item.name + "Has been Successfully Updated", "success")
        except ShoppingListDoesNotExist:
            flash(
                "No Shopping List With name " + shopping_list_name +
                " Try Adding it instead", "warning")
        except ItemDoesNotExist:
            flash(
                "Sorry Item " + item.name +
                " Cannot Be Updated. Make sure you have such item first",
                "warning")
        return redirect(url_for('index'))
    else:
        return render_template("update_item.html",
                               form=form,
                               shopping_list_name=shopping_list_name,
                               item=item_to_update)
示例#4
0
def populate():
    """Populate database with dummy data."""
    description = (
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer '
        'dignissim arcu vitae placerat vestibulum. Donec nec augue diam. Donec '
        'lobortis laoreet turpis vehicula faucibus. Cras scelerisque consequat '
        'tempus. Maecenas arcu urna, auctor a cursus in, sodales quis dui. Cum '
        'sociis natoque penatibus et magnis dis parturient montes, nascetur '
        'ridiculus mus. Nunc ex ipsum, dapibus sed nunc quis, porta laoreet '
        'neque. Etiam nec fringilla lacus. Ut viverra tincidunt leo id tempor.'
    )
    items = [
        ('ball', 'soccer', description),
        ('stick', 'basketball', description),
        ('goggles', 'soccer', description),
        ('snowboard', 'soccer', description),
        ('shinguards', 'frisbee', description),
        ('frisbee', 'soccer', description),
        ('bat', 'soccer', description),
        ('raquette', 'soccer', description),
        ('helmet', 'soccer', description),
        ('gloves', 'soccer', description),
        ('net', 'soccer', description),
        ('ball', 'basketball', description),
        ('disk', 'soccer', description),
        ('boots', 'soccer', description),
        ('sock', 'soccer', description),
    ]
    for item in items:
        if not Catagory.exists(item[1]):
            catagory = Catagory.create(name=item[1])
        Item.create(item[0], catagory_name=item[1], description=item[2])
示例#5
0
def dummy_items(test_db):
    ItemTuple = namedtuple('Item', ['name', 'catagory', 'description'])
    items = [
        ItemTuple('ball', 'soccer', 'a soccer ball'),
        ItemTuple('stick', 'basketball', 'a basketball stick'),
        ItemTuple('goggles', 'soccer', ''),
        ItemTuple('snowboard', 'soccer', ''),
        ItemTuple('shinguards', 'frisbee', ''),
        ItemTuple('frisbee', 'soccer', ''),
        ItemTuple('bat', 'soccer', ''),
        ItemTuple('raquette', 'soccer', ''),
        ItemTuple('helmet', 'soccer', ''),
        ItemTuple('gloves', 'soccer', ''),
        ItemTuple('net', 'soccer', ''),
        ItemTuple('ball', 'basketball', ''),
        ItemTuple('disk', 'soccer', ''),
        ItemTuple('boots', 'soccer', ''),
        ItemTuple('sock', 'soccer', ''),
    ]
    for item in items:
        if Catagory.exists(item.catagory):
            Item.create(item.name,
                        catagory_name=item[1],
                        description=item.description)
        else:
            catagory = Catagory.create(name=item[1])
            Item.create(item.name,
                        catagory=catagory,
                        description=item.description)
    return items
示例#6
0
def test_create_uses_catagory_name_arg_when_passed(mock, mock_session):
    mock_init = mock.patch('app.models.item.Item.__init__', return_value=None)
    Item.create('an item',
                catagory_name='a catagory',
                description='description')
    mock_init.assert_called_once_with(name='an item',
                                      catagory=mock.ANY,
                                      description='description')
示例#7
0
def item_init():
    for item in item_list:
        cat_name = item['category']
        c_id = Category.getIdByName(cat_name)
        # assert(c_id)
        Item.create(name=item['name'],
                    description=item['description'],
                    category_id=c_id)
示例#8
0
 def generate():
     yield '{"items": ['
     for offset_ in range(0, total_items, chunk_size):
         if (offset_ + chunk_size) >= total_items:
             yield json.dumps(Item.get_catalogue_uuids(type_, offset_=offset_, limit_=chunk_size))
         else:
             yield json.dumps(Item.get_catalogue_uuids(type_, offset_=offset_, limit_=chunk_size)) + ', '
     yield '], "message": "finished"}'
示例#9
0
def update_item():
    """
    Update the requested item.
    """

    # Get the category and check if it's exist or fail to 404 page if not
    category = Category.find_or_fail(request.form['category_id'])

    # Get the item and check if it's exist or fail to 404 page if not
    item = Item.find_or_fail(request.form['item_id'])

    # Make sure the current user is authorized or not
    if not item.user or item.user.id != current_user.id:
        return current_app.login_manager.unauthorized()

    # The below is for validate the unique slug, if it
    # was exists before, then the ORM will not fall to
    # the ModelNotFound exception and the code will
    # continue flashing the error message to the user.
    # Otherwise, if the slug is not exists, then the
    # request is completely valid and the ORM will
    # going to fall to the ModelNotFound exception
    # then save the new Item
    try:
        # Get the current item slug before it changing using ORM mutator
        old_item_slug = item.slug

        item.title = request.form['title']
        item.description = request.form['description']

        # Associate the new item with the category
        item.category().associate(category)

        # Associate the new item to the current user
        item.user().associate(current_user)

        # Get the item and check if it's exist or fail to 404 page if not
        Item.where('slug', item.slug).first_or_fail()

        # if the current slug is the same as requested then throw
        # to the ModelNotFound Exception and save the current item
        if item.slug == old_item_slug:
            raise ModelNotFound(item.__class__)

        flash('The title seems similar to another'
              ' title, please choose another one.')

        return render_template('items/edit.html',
                               categories=Category.all(),
                               item=item)
    except ModelNotFound:
        # Save the item
        item.save()

    return redirect(
        url_for('view_item', category_slug=category.slug, item_slug=item.slug))
示例#10
0
def test_dict(mock_session):
    item = Item()
    item.name = 'x'
    item.catagory_id = 2
    item.description = 'z'
    assert item.dict == {
        'id': None,
        'catagory_id': 2,
        'name': 'x',
        'description': 'z'
    }
示例#11
0
    def setUp(self):
        """This method sets up the variables for the tests"""
        self.item_1 = Item('Soap', 2500)
        self.item_2 = Item('Pringles', 7500)
        self.item_3 = Item('Cake', 10000)

        self.items = {
            self.item_1.name: self.item_1,
            self.item_2.name: self.item_2
        }
        self.shopping_list_1 = ShoppingList('From the farmers market', {})
        self.shopping_list_2 = ShoppingList('From the supermarket', self.items)
示例#12
0
def deleteItem(item_id):
    # Validate item_id
    item = Item.getItemById(item_id)
    if not item:
        flash('Item {} not found'.format(item_id))
        return redirect_back('main.homepage')

    next = get_redirect_target()
    if request.method == 'POST':
        Item.delete(item_id)
        flash("{} deleted".format(item.name))
        return redirect(url_for('main.homepage'))
    else:
        return render_template('item_delete.html', item=item, next=next)
    def test_similar_get(self):
        """Test case for similar_get

        Returns the set of items ordered by similarity, compared to the given item
        """
        body = ItemSet(
            data=[Item(id='1', name="car bmw"),
                  Item(id='2', name='car')])
        response = self.client.open('/similar/{id}'.format(id='1'),
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')

        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
示例#14
0
def editItem(item_id):
    item = Item.getItemById(item_id)
    if not item:
        flash("Item () note found").form(item_id)
        return redirect(url_for(main.homepage))

    next = get_redirect_target()
    form = ItemForm(next=next)
    form.category.choices = [(category.id, category.name)
                             for category in Category.getAll()]

    if request.method == 'GET':
        form.name.data = item.name
        form.description.data = item.description
        form.category.data = item.category_id
        form.category.choices = [(category.id, category.name)
                                 for category in Category.getAll()]
        return render_template('item_form.html',
                               form=form,
                               name=item.name,
                               description=item.description,
                               category=item.category)

    if form.validate_on_submit():
        item.name = form.data['name']
        item.description = form.data['description']
        cat_id = form.data['category']
        item.category_id = form.data['category']
        db.session.commit()
        return redirect_back('main.homepage')
示例#15
0
def displayItem(item_id):
    item = Item.getItemById(item_id)
    if not item:
        flash('Item {} not found'.format(item_id))
        return redirect('main.homepage')

    return render_template("item_details.html", item=item, user=current_user)
示例#16
0
 def add_book(self, title, subtitle, add_item=False):
     """ Add book (as description) to database """
     b = Book(title=title, subtitle=subtitle)
     db.session.add(b)
     db.session.commit()
     if add_item:
         self.new_item(Item(book=b))
示例#17
0
def newitem():
    name = None
    description = None
    category = None
    next = get_redirect_target()
    form = ItemForm(next=next)
    form.category.choices = \
        [(category.id, category.name) for category in Category.getAll()]

    if form.validate_on_submit():
        name = form.name.data
        description = form.description.data
        category_id = form.category.data
        item = Item(name=name,
                    description=description,
                    category_id=category_id)
        db.session.add(item)
        db.session.commit()
        flash("Item {} created".format(name))
        return redirect_back('main.homepage')

    return render_template('item_form.html',
                           form=form,
                           name=name,
                           description=description,
                           category=category)
示例#18
0
def get_it_list():
    ''' Get list of all items with their given 
        id and name
            @Params:
                - p
                - ipp
    '''
    logger.debug("List items")
    params = request.args
    # Validation
    if not params:
        raise errors.ApiError(70001, "Missing required key params")

    _needed_params = {'p', 'ipp'}
    if not _needed_params.issubset(params.keys()):
        raise errors.ApiError(70001, "Missing required key params: {}".format(list(_needed_params)))

    if 'cols' not in params:
        cols = ','.join(['description'])
    else:
        cols = params['cols']

    _resp = Item.it_list(cols=cols, p=params['p'], ipp=params['ipp'])

    if params.get('csv', '0') == '1':
        csv_ = pd.DataFrame(_resp, dtype=str).to_csv(quoting=csv.QUOTE_ALL)
        return Response(
        csv_,
        mimetype="text/csv",
        headers={"Content-disposition":
                "attachment; filename=item_data.csv"})
    return jsonify({
        "status": "OK",
        "items": _resp
    })
示例#19
0
def edit_item(category_slug, item_slug):
    """
    Edit the current item form.

    :param category_slug: The category slug
    :param item_slug: The item slug
    """

    # Get the item and check if it's exist or fail to 404 page if not
    item = Item.where('slug', item_slug).first_or_fail()

    # Make sure the current user is authorized or not
    if not item.user or item.user.id != current_user.id:
        return current_app.login_manager.unauthorized()

    # Get the category slug from url and compare it with the item's
    # category slug, if both are not the same, redirect to the correct slug
    if category_slug != item.category.slug:
        return redirect(
            url_for('edit_item',
                    category_slug=item.category.slug,
                    item_slug=item.slug))

    return render_template('items/edit.html',
                           categories=Category.all(),
                           item=item)
示例#20
0
def query_by(by):
    """ Endpoint to query items table by given values

        @Params:
            - by: <str> column to compare values with
            - keys: <str> can be item_uuid, gtin, name, description

        @Response:
            - resp: items list
        
        @Example:
            /query/gtin?keys=07501034691224,07501284858385
    """
    logger.info("Query Items by Item UUID...")
    params = request.args.to_dict()
    logger.debug(params)
    # Validate required params
    _needed_params = {'keys'}
    if not _needed_params.issubset(params):
        raise errors.ApiError(70001, "Missing required key params")
    # Complement optional params, and set default if needed
    _opt_params = {'cols': '', 'p':1, 'ipp': 50}
    for _o, _dft  in _opt_params.items():
        if _o not in params:
            params[_o] = _dft
    _items = Item.query(by, **params)
    return jsonify({
        'status': 'OK',
        'items': _items
    })
示例#21
0
def add_item(shopping_list_name):
    form = AddItem()
    if form.validate_on_submit():
        """ 
        Instantiate an Item Object from the 
        form data submitted by the current_user
        """
        item = Item(form.item_name.data, form.item_price.data,
                    form.item_quantity.data, form.category.data)
        try:
            shopping_list = current_user.get_shopping_lst(shopping_list_name)
            shopping_list.add_item(item)
            current_user.update_shopping_list(shopping_list)
            flash(
                " " + item.name + " Successfully Added into Shopping List " +
                shopping_list_name, "info")

            return redirect(url_for('index'))

        except ItemAlreadyExist:
            flash(item.name + " Already Exists Try updating it instead",
                  "info")
            return redirect(url_for('index'))
    else:
        return render_template("add_item.html",
                               form=form,
                               shopping_list_name=shopping_list_name)
示例#22
0
def details_info():
    """ Endpoint to get details of given items

        @Params:
            - values: <str> list of values
            - by: <str> field which the values are queried against
                (WHERE <by> = <value>)
            - cols: <str> can be item_uuid, gtin, name, description

        @Response:
            - resp: items list
    """
    logger.info("Info details")
    params = request.args
    # Validation
    if not params:
        raise errors.ApiError(70001, "Missing required key params")

    # Verify needed key-values
    _needed_params = {'values', 'by'}
    if not _needed_params.issubset(params.keys()):
        raise errors.ApiError(70001, "Missing required key params")

    if 'cols' not in params:
        cols = ['item_uuid', 'gtin', 'name', 'description']

    # Call to delete Item
    values = params['values'].split(",")
    by = params['by']
    _resp = Item.get(values, by=by, _cols=cols)
    return jsonify({
        "status": "OK",
        "items": _resp
    })
示例#23
0
def get_by_filters():
    filters = request.get_json()
    items = Item.get_by_filters(filters)
    print(items)
    if not items:
        return jsonify([])
    brands = Brand.get_by_items([i['item_uuid'] for i in items])
    return jsonify(brands)
示例#24
0
def get_one():
    """
        Testing connection method
    """
    logger.debug("Testing connection with one product")
    prod = Item.get_one()
    if not prod:
        raise errors.ApiError("invalid_request", "Could not fetch data from Postgres Items")
    return jsonify(prod)
示例#25
0
def vademecum_info():
    """ Endpoint to get info from vademecum
    """
    logger.info("Fetching Vademecum additonal info..")
    params = request.args
    if 'uuid' not in params:
        raise errors.ApiError(70001, "Missing required UUID param")
    # Call values
    _resp = Item.get_vademecum_info(params['uuid'])
    return jsonify(_resp)
示例#26
0
def details_item():
    """ Endpoint to get details for FrontEnd info
    """
    logger.info("Item details endpoint...")
    params = request.args
    # Validation
    if not params:
        raise errors.ApiError(70001, "Missing required key params")
    _needed_params = {'uuid'}
    if not _needed_params.issubset(params.keys()):
        raise errors.ApiError(70001, "Missing required key params")
    # Verify if item or product
    uuid_type = 'item_uuid'
    if not Item.exists({'item_uuid': params['uuid']}):
        uuid_type = 'product_uuid'
    _resp = Item.details(uuid_type, params['uuid'])
    logger.debug(_resp)
    logger.info("Delivering response: {}".format(params['uuid']))
    return jsonify(_resp)
示例#27
0
def home(category_id=None):
    categories = Category.getAll()
    category = None

    # Category is not specified.  Show latest items
    if not category_id:
        items = Item.getItemsByDate()
    # Show items for specified category
    else:
        category_id = int(category_id)
        for category in categories:
            if category.id == category_id:
                break

        items = Item.getItemsByCategory(category_id=category_id)
    return render_template("home.html",
                           categories=categories,
                           items=items,
                           category=category)
示例#28
0
def post(user_id):
    postData = json.loads(str(request.data, encoding='utf-8'))
    print('postData', postData)
    # TODO 数据校验
    user = User.query.get(user_id)
    if Item.createItemByPostData(postData, user_id) and user.update_tel(
            postData['tel']):
        cache.delete_like(cache, 'get_item')  # 有新增数据,删除item相关缓存
        return jsonify(Res(1, 'post item successfully').raw())
    return jsonify(Res(0, 'something error').raw())
    def get(self, shopping_id=None):
        if shopping_id != None:
            items = Item.get_all_by_id(shopping_id)
        else:
            items = Item.get_all()

        results = []
        for item in items:
            obj = {
                'id': item.item_id,
                'quantity': item.quantity,
                'item_name': item.item_name,
                'date_created': item.date_created
            }
            results.append(obj)

        response = jsonify(results)
        response.status_code = 200
        return response
示例#30
0
def modify_item():
    """ Endpoint to modify a new `Item`
    """
    logger.info("Modify Item...")
    params = request.get_json()
    logger.debug(params)
    if not params:
        raise errors.ApiError(70001, "Missing required key params")
    # Verify needed key-values
    _needed_params = {'item_uuid'}
    if not _needed_params.issubset(params.keys()):
        raise errors.ApiError(70001, "Missing required key params")
    # Call to save Item
    _item = Item(params)
    _item.save()
    return jsonify({
        "status": "OK",
        "message": _item.message,
        "item_uuid": _item.item_uuid
    })