Example #1
0
    def get_products(self):
        """
        function parses the products xml file
        and returns list of products
        """

        lst = []
        for product in self.products.findall('product'):
            id = product.find('id').text
            name = product.find('name').text
            dispensary_id = product.find('dispensary_id').text
            dispensary_name = product.find('dispensary_name').text
            canabis_brand = product.find('canabis_brand').text
            canabis_strain = product.find('canabis_strain').text
            category = product.find('category').text
            subcategory = product.find('subcategory').text
            thc_level = product.find('thc_level').text
            cbd_level = product.find('cbd_level').text
            cbn_level = product.find('cbn_level').text
            thc_level_type = product.find('thc_level_type').text
            cbd_level_type = product.find('cbd_level_type').text
            cbn_level_type = product.find('cbn_level_type').text

            description = product.find('description').text
            created_at = product.find('created_at').text
            updated_at = product.find('updated_at').text

            prices = []
            urls = []
            images = []

            for child in product:
                if child.tag == 'prices':
                    for cost in child.findall('cost'):
                        prices.append(Price(cost.attrib['unit'], cost.text))

                if child.tag == 'urls':
                    admin = child.find('admin').text
                    public = child.find('public').text
                    urls.append(UrlInfo(admin, public))

                if child.tag == 'images':
                    for image in child.findall('image'):
                        images.append(Image(image.attrib['main'], image.text,))

            lst.append(Product(id, name, dispensary_id, dispensary_name,
                               canabis_brand, canabis_strain,
                               category, subcategory, thc_level, cbd_level,
                               cbn_level, thc_level_type, cbd_level_type,
                               cbn_level_type, prices, urls, images,
                               description, created_at, updated_at))

        return lst
Example #2
0
def create_product():
    try:
        body = request.stream.read().decode('utf-8')
        data = json.loads(body)
        product = Product(id=data.get('id'),
                          name=data['name'],
                          price=Decimal(data['price']))
        db.session.add(product)
        db.session.commit()
    except (ValueError, KeyError) as e:
        return Response(str(e), 400)
    return body
Example #3
0
def showAllProducts():
    if request.method == 'GET':
        products = session.query(Product).all()
        return jsonify(products=[p.serialize for p in products])
    if request.method == 'POST':
        name = request.json.get('name')
        category = request.json.get('category')
        price = request.json.get('price')
        newItem = Product(name=name, category=category, price=price)
        session.add(newItem)
        session.commit()
        return jsonify(newItem.serialize)
Example #4
0
 def post(self):
     name = request.form.get('name')
     price = request.form.get('price')
     product = Product(name, price)
     db.session.add(product)
     db.session.commit()
     return jsonify({
         product.id: {
             'name': product.name,
             'price': str(product.price),
         }
     })
Example #5
0
 def test_0a_1_2_2_MyModel(self):
     try:
         product = Product(name="Cheese",
                           price=50.4,
                           quantity=7.89,
                           code=789456611,
                           bla="123")
     except Exception as e:
         self.assertEqual(
             str(e),
             "'bla' is an invalid " + "keyword argument for Product")
     print("Test 0a_1_2_2 : MyModel: success")
Example #6
0
    def test_a_1_001_product_insert(self):
        db_drop_and_create_all()
        product1 = Product(name="Cheese",
                           price=50.4,
                           quantity=7.89,
                           id=10000000,
                           code=789456611)
        product1.insert()
        products = Product.query().all()

        self.assertEqual(len(products), 1)
        print("Test a_1_1: product insert")
Example #7
0
def fill_offer_with_new_data(product_dict: str, user: User) -> Offer:
    product = Product()
    url = product_dict.get('url')
    if url:
        is_url_safe(url)
        product_dict['isNational'] = True
    product.populate_from_dict(product_dict)
    check_user_can_create_activation_event(user, product)
    offer = Offer()
    offer.populate_from_dict(product_dict)
    offer.product = product
    return offer
Example #8
0
 def test_add_a_product(self):
     """ Create a product and add it to the database """
     p = Product.all()
     self.assertEqual(p, [])
     p = Product(0, 'Asus2500', 'Laptop', '234', 'laptop', 'blue', 4)
     self.assertTrue(p != None)
     self.assertEqual(p.id, 0)
     p.save()
     # Asert that it was assigned an id and shows up in the database
     self.assertEqual(p.id, 1)
     products = Product.all()
     self.assertEqual(len(products), 1)
    def post(self):
        """Create a new product.

        :return:
        """
        data = validate_data(request.get_json(), product_schema)
        product = Product(**data)
        db.session.add(product)
        db.session.commit()

        oms_client.register_product(product)  # TODO could use background worker
        return product_schema.dump(product), 201
Example #10
0
def fetch_category(search_index, amazon_node_id):
    api = caching.ResponseCachingAPI(settings.AMAZON_AWS_KEY,
                                     settings.AMAZON_SECRET_KEY,
                                     settings.AMAZON_API_LOCALE,
                                     settings.AMAZON_ASSOCIATE_TAG,
                                     cachedir='cache',
                                     cachetime=86400)

    try:
        for root in api.item_search(
                search_index,
                BrowseNode=str(amazon_node_id),
                ResponseGroup=settings.AMAZON_RESPONSE_GROUP):

            for item in root.Items.Item:
                product = Product()
                product.category = Category.objects.get(
                    amazon_node_id=amazon_node_id)
                product.asin = item.ASIN
                product.title = unicode(item.ItemAttributes.Title)
                product.detailpageurl = unicode(item.DetailPageURL)
                product.manufacturer = unicode(
                    getattr(item.ItemAttributes, 'Manufacturer', None))
                product.publisher = unicode(
                    getattr(item.ItemAttributes, 'Publisher', None))
                product.brand = unicode(
                    getattr(item.ItemAttributes, 'Brand', None))
                product.popularity = getattr(item, 'SalesRank', 1000)
                if hasattr(item, 'MediumImage'):
                    product.medium_image = getattr(item.MediumImage, 'URL',
                                                   None)
                if hasattr(item, 'LargeImage'):
                    product.large_image = getattr(item.LargeImage, 'URL', None)
                if hasattr(item, 'EditorialReviews'):
                    product.description = unicode(
                        getattr(item.EditorialReviews.EditorialReview,
                                'Content', None))
                if hasattr(item.Offers, 'Offer'):
                    product.price = item.Offers.Offer.OfferListing.Price.FormattedPrice.pyval
                elif hasattr(item.ItemAttributes, 'ListPrice'):
                    product.price = item.ItemAttributes.ListPrice.FormattedPrice.pyval
                elif hasattr(item.OfferSummary, 'LowestUsedPrice'):
                    product.price = u'used from %s' % item.OfferSummary.LowestUsedPrice.FormattedPrice.pyval
                else:
                    product.price = None
                product.save()

    except AWSError, e:
        if e.code == 'AWS.ParameterOutOfRange':
            pass  # reached the api limit of 10 pages
        else:
            raise ValidationError(message=e.msg)
Example #11
0
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        file_obj = request.files['file']

        if file_obj.filename == '' or file_obj.filename.split(
                '.')[-1] != 'tsv':
            error = 'Invalid file!'
            return render_template('upload.html', error=error)

        if file_obj:
            filename = secure_filename(file_obj.filename)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file_obj.save(file_path)

        with open(file_path) as order_data:
            reader = csv.reader(order_data, delimiter='\t')

            app.logger.info('Begin processing File')

            for row in reader:
                customer, product, order_status, previous_order = process_order(
                    row)

                if not previous_order:
                    insert_row(db.session, Customer(**customer), app.logger)
                    db.session.commit()

                    insert_row(db.session, Product(**product), app.logger)
                    db.session.commit()

                    insert_row(db.session, OrderStatus(**order_status),
                               app.logger)
                    db.session.commit()

                else:
                    order = OrderStatus.query.filter_by(
                        status='new', **previous_order).first()

                    if order:
                        order.status = 'canceled'
                        order.updated_at = order_status['updated_at']
                    else:
                        app.logger.warn(
                            'Unable to load row: {}'.format(order_status))

                    db.session.commit()

        return redirect(url_for('uploaded_file', filename=filename))
Example #12
0
 def add(uid, name, description=''):
     """添加产品
     """
     product = Product.query.filter(Product.name == name).first()
     if product:
         product.name = name
         product.description = description
         product.modified_by = uid
         product.update()
     else:
         product = Product(name, description, uid, uid)
         product.save()
     return product
Example #13
0
def add() -> None:
    "Add Fitchen to the database"
    fitchen = Location()
    fitchen.configure("Fitchen", "?", "?", "https://www.fitchen.be/")
    db.session.add(fitchen)

    for menuitem in menuitems:
        for size, price in pricedict.items():
            for container in ["bowl", "wrap"]:
                name = "%s %s in %s" % (size, menuitem, container)
                entry = Product()
                entry.configure(fitchen, name, price)
                db.session.add(entry)
Example #14
0
def add_product(current_user):
    name = request.json['name']
    description = request.json['description']
    price = request.json['price']
    qty = request.json['qty']
    user_id = current_user.id

    new_product = Product(name, description, price, qty, user_id)

    db.session.add(new_product)
    db.session.commit()

    return product_schema.jsonify(new_product)
Example #15
0
def test_product_simple(session):
    p1 = Product("test1", 1.0, "description 1")
    session.add(p1)
    session.commit()
    assert p1.name == "test1"
    assert p1.price == 1.0
    assert p1.description == "description 1"
    assert p1.to_dict() == {
        "pk": 1,
        "name": "test1",
        "price": 1.0,
        "description": "description 1",
    }
Example #16
0
def create_product():
    requested_object = request.get_json()
    new_object = Product()
    try:
        for attr in ['name', 'description']:
            setattr(new_object, attr, requested_object[attr])
    except KeyError:
        return '', 400

    db.session.add(new_object)
    db.session.commit()

    return product_schema.jsonify(new_object)
def products():
    if request.method=="GET":
        products = db.session.query(Product).all() # SQLAlchemy request => 'SELECT * FROM products'
        return products_schema.jsonify(products)
    if request.method=="POST":
        json=request.json
        prod = Product()
        prod.name = json["name"]
        prod.description = json["description"]
        db.session.add(prod)
        db.session.commit()
        #insert product
        return product_schema.jsonify(prod)
Example #18
0
def add_product():
    data = request.get_json()

    try:
        print(data)
        if type(data['price']) is not int:
            raise ValueError('Price should be integer')
        product = Product(data['id'], data['name'], data['price'])
        products.append(product)
    except ValueError as e:
        print(e)
        return jsonify({'message': 'Price should be integer'}), 400
    return jsonify({'products': [product.to_json()]}), 201
Example #19
0
def csv_to_json():
    list = []
    try:
        with open('data/brand2.csv', 'r') as f:
            reader = csv.DictReader(f)
            next(reader)
            for row in reader:
                j = json.loads(json.dumps(dict(row)))
                product = Product(**j)
                list.append(product.toJSON())
        return list
    except Exception as e:
        logging.error(traceback.format_exc())
    def post(self):

        app.logger.info('Request to Create a Product')
        check_content_type('application/json')
        prod = Product()
        app.logger.info('Payload = %s', api.payload)
        mqtt.publish('myTopic', str(api.payload))
        prod.deserialize(api.payload)
        location_url = api.url_for(ProductResource,
                                   products_id=prod.id,
                                   _external=True)
        return prod.serialize(), status.HTTP_201_CREATED, \
            {'Location': location_url}
Example #21
0
 def create_product(request):
     name = request.form['name']
     description = request.form['description']
     price = request.form['price']
     if not name or not description or not price:
         flash("enter all the field")
     else:
         product = Product(name,description,price)
         db.session.add(product)
         db.session.commit()
         flash("create succed")
     result = product
     return result
Example #22
0
    def test_get_product(self):
        """Test retrieving customer item from db"""
        product = Product(ean="123", stock=1)

        db.session.add(product)
        db.session.commit()

        result = self.client.get('/product/1')
        self.assertEqual(result.status_code, 200)

        data = json.loads(result.data)
        self.assertEqual(data['ean'], '123')
        self.assertEqual(data['stock'], 1)
def insertpro():
    if request.method == 'POST':

        product_name = request.form['product_name']
        product_qty = request.form['quantity']
        from models import Product

        my_data = Product(product_name, product_qty)
        db.session.add(my_data)
        db.session.commit()
        flash("Add Product Successfully")

        return redirect(url_for('product'))
Example #24
0
def create_product():
    #pdb.set_trace()
    data = request.get_json()
    name = data.get('name')
    description = data.get('description')

    objProduct = Product()
    objProduct.name = name
    objProduct.description = description
    db.session.add(objProduct)
    db.session.commit()

    return ''
Example #25
0
    def fill_product_and_branch_price_tables(self, information_list,
                                             branch_id):  # pylint: disable=too-many-locals
        """
        This method receives a list containing a tuple of all the xml info
        and places it into the correct table
        :param information_list: list of tuples containing all the xml info
        :param branch_id: the id of the current branch
        :return: two lists, one containing Product obj the other BranchPrice objects
        """
        branch_price_list = []
        product_info_list = []

        for item_code, item_name, quantity, is_weighted, unit_of_measure, price, update_date in information_list:  # pylint: disable=line-too-long
            # If the item is not in the db , add it
            if item_code not in self.item_id_set:
                product_info_list.append(
                    Product(id=item_code,
                            name=item_name,
                            quantity=quantity,
                            is_weighted=is_weighted,
                            unit_of_measure=unit_of_measure))
                self.item_id_set.add(item_code)

            # if not in the db then add it
            if (self.current_super['chain_id'], item_code, int(branch_id)) not in \
                    self.branch_price_unique_constraint_set:
                branch_price_list.append(
                    BranchPrice(chain_id=self.current_super['chain_id'],
                                branch_id=branch_id,
                                item_code=item_code,
                                price=price,
                                update_date=update_date))
                self.branch_price_unique_constraint_set.add(
                    (self.current_super['chain_id'], item_code,
                     int(branch_id)))
            else:
                current_branch_list = self.session.query(
                    BranchPrice).filter_by(
                        chain_id=self.current_super['chain_id'],
                        item_code=item_code,
                        branch_id=branch_id).all()
                if current_branch_list:
                    current_branch = current_branch_list[0]
                    old_price = current_branch.price
                    # update the price if it has changed
                    if old_price != price:
                        current_branch.price = price

                    self.session.flush()

        return product_info_list, branch_price_list
Example #26
0
def new_product(request, template_name="catalog/new.html"):
    categories = Category.objects.all()
    product = Product()
    if request.user.is_authenticated():
        if request.method == "POST":
            form = productForm(request.POST, request.FILES)
            if form.is_valid():
                saves = Product(name=request.POST['name'],
                                price=request.POST['price'],
                                old_price=request.POST['old_price'],
                                quantity=request.POST['quantity'],
                                description=request.POST['description'],
                                meta_keywords=request.POST['name'].split(),
                                image=request.FILES['photo'],
                                meta_description="none",
                                created_at=datetime.datetime.now(),
                                updated_at=datetime.datetime.now(),
                                is_bestseller=True,
                                is_active=True,
                                is_featured=True,
                                user=request.user,
                                slug=request.POST['name'].strip().replace(
                                    ' ', '_').lower())

                saves.save()
                for c in request.POST.getlist('categories'):
                    saves.categories.add(c)
                    update()
                return HttpResponseRedirect('/')
        else:
            form = productForm()
    else:
        return HttpResponseRedirect('/accounts/login/')
    return render_to_response(template_name, {
        'form': form,
        'categories': categories,
    },
                              context_instance=RequestContext(request))
def postProduct():

    new_product = json.loads(request.data)
    product = Product(sku_id=new_product["sku_id"],
                      name=new_product["name"],
                      description=new_product["description"],
                      quantity=new_product['quantity'],
                      price=new_product["price"],
                      supplier_id=new_product["supplier_id"])

    db.session.add(product)
    db.session.commit()

    return jsonify({"exitoso": product.serialize()}), 200
Example #28
0
    def add_product(self, product_list):
        """

        :param product_list: a list of dictionaries. Each dictionary represents a product
        :return: a list of products
        """
        final_list = {}
        increment = 0
        for product in product_list:
            print(product)
            p = Product(product['name'], product['price'], product['stock'], product['updated'])
            final_list[0] = product
            increment += 1
        return final_list
Example #29
0
def show_all_products():
    if request.method == 'GET':
        products = session.query(Product).all()
        return jsonify(products=[p.serialize for p in products])
    if request.method == 'POST':
        name = request.json.get('name')
        category = request.json.get('category')
        price = request.json.get('price')
        if not name or not category or not price:
            return jsonify(error="faltan campos")
        new_item = Product(name=name, category=category, price=price)
        session.add(new_item)
        session.commit()
        return jsonify(new_item.serialize)
def addItem():
    if request.method=='GET':
        return render_template('addItem.html')
    else:
        product_name=request.form.get('product_name')
        inventory=request.form.get('inventory')
        product=Product(product_name=product_name,inventory=inventory)
        db.session.add(product)
        db.session.commit()
        contexts = {
            'products': Product.query.all(),
            'edgeOb': Edge.query.filter(Edge.id != -1).order_by(Edge.id.desc()).first()
        }
        return render_template('manager.html',**contexts)