Exemplo n.º 1
0
def add_product(name, price, picture_link, description):

    product_object = Product(name=name,
                             price=price,
                             picture_link=picture_link,
                             description=description)
    session.add(product_object)
    session.commit()
Exemplo n.º 2
0
 async def fetch_async(url):
     async with aiohttp.ClientSession() as session:
         async with session.get(url) as resp:
             print(resp.status)
             data = await resp.text()
             p = Product()
             p.parse(data)
             print(p.__dict__)
             return p
def add_Product(name, price, Picture_link, Description):
	session = con()
	Product_object = Product(
				name=name,
				price=price,
				Picture_link=Picture_link,
				Description=Description)
	session.add(Product_object)
	session.commit()
Exemplo n.º 4
0
def add_product(name, price, picture_link, description):
    session = create_session()
    product_object = Product(name=name,
                             price=price,
                             picture_link=picture_link,
                             description=description)
    session.add(product_object)
    session.commit()
    session.close()
Exemplo n.º 5
0
def generate_add_product(name, price, seller, category, new_count):
    for product_id, value_products in products.items():
        if value_products[0].name == name:
            value_products[1] += new_count
            return value_products[0]

    new_product = Product(name, price, seller, category)
    products[new_product.id] = [new_product, new_count]
    return new_product
Exemplo n.º 6
0
def add_product(name, price, Picture, Description):

    product_object = Product(
        name=name,
        price=price,
        Picture =String,
        Description =Description)
    session.add(product_object)
    session.commit()
Exemplo n.º 7
0
def create_product():
    print('Existing products:')
    options_list(Product)
    name = input("\nName: ")
    price = input("Price: ")
    product = Product(name=name, price=price)
    session.add(product)
    session.commit()
    print('created!\n')
Exemplo n.º 8
0
def add_product(id, name, price, price_link, description ):
    product_object = Product(
        ID=id,
        Name=name,
        Price=price,
        price_link=price_link,
        Description=discription,)
    session.add(product_object)
    session.commit()
Exemplo n.º 9
0
def add_product(name, price, Picture_Link,Description):

    product = Product(
        name=name,
        price=price,
        Picture_Link=Picture_Link,
        Description=Description)
    session.add(product)
    session.commit()
Exemplo n.º 10
0
def create_product(product_name, session=None):
    product_name = product_name.upper()
    products = session.query(Product).filter(Product.id == product_name).all()
    if len(products):
        return com.error(com.WARN_EXISTING_CATEGORY)
    else:
        p = Product(id=product_name)
        session.add(p)
        session.commit()
    return com.success()
Exemplo n.º 11
0
def buy_intent(product_name):
    products = Product(context.System.apiAccessToken)
    logger.info("PRODUCT: {}".format(product_name))
    buy_card = render_template('buy_card', product=product_name)
    productId = products.productId(product_name)
    if productId is not None:
        session.attributes[PRODUCT_KEY] = productId
    else:
        return statement("I didn't find a product {}".format(product_name))
        raise NotImplementedError()
    return buy(productId).simple_card('Welcome', question_text)
Exemplo n.º 12
0
def create_product(name, brand, product_categorization, image=''):
    """Create, add to db, and return a new product."""

    product = Product(name=name,
                      brand=brand,
                      product_categorization=product_categorization,
                      image=image)

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

    return product
Exemplo n.º 13
0
def products_to_db(filename):
    """Reads the items.json file and stores all the items in the kart database."""

    with open(filename, 'r') as filename:
        for item in json.load(filename):
            product = Product(name=item)

            db.session.add(product)

    print 'Now committing!'
    db.session.commit()
    print 'Committed!'
Exemplo n.º 14
0
def refund_intent(product_name):
    refund_card = render_template('refund_card')
    logger.info("PRODUCT: {}".format(product_name))

    products = Product(context.System.apiAccessToken)
    productId = products.productId(product_name)

    if productId is not None:
        session.attributes[PRODUCT_KEY] = productId
    else:
        raise NotImplementedError()
    return refund(productId)
Exemplo n.º 15
0
 def load_products(self, products_file):
     items = FileUtil.load_csv(products_file)
     for pid, name, tname, tid, year, pdf, image in items:
         self.products.append(
             Product(product_id=pid,
                     name=name,
                     theme=tid,
                     store_folder=self.store_folder,
                     theme_name=tname,
                     launch_year=year,
                     pdf_locations=[pdf],
                     images=[image]))
Exemplo n.º 16
0
def load_products():
    """Load products into database"""

    print "Products"
    product_id = 0
    with open('items.json') as file:
        for title in file:
            title = title.rstrip().strip(',')
            product = Product(product_id=product_id, title=title)
            product_id += 1
            db.session.add(product)
        db.session.commit()
Exemplo n.º 17
0
def create_product(form):
    try:
        with create_session() as s:
            p = Product(form)
            if _get_products([p.sku], s):
                return 'Existed'
            else:
                s.add(p)
                return p.sku
    except:
        raise
        return 'Failed'
Exemplo n.º 18
0
def create_product(brand, name, category, tag, img_path):
    """Create and return a new product."""

    product = Product(brand=brand,
                      name=name,
                      category=category,
                      tag=tag,
                      img_path=img_path)

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

    return product
Exemplo n.º 19
0
def completed(payload, name, status, token):
    products = Product(context.System.apiAccessToken)
    logger.info('on-purchase-completed {}'.format( request))
    logger.info('payload: {} {}'.format(payload.purchaseResult, payload.productId))
    logger.info('name: {}'.format(name))
    logger.info('token: {}'.format(token))
    logger.info('status: {}'.format( status.code == 200))
    product_name = products.productName(payload.productId)
    logger.info('Product name'.format(product_name))
    if status.code == '200' and ('ACCEPTED' in payload.purchaseResult):
        return question('To listen it just say - play {} '.format(product_name))
    else:      
        return question('Do you want to buy another product?')
Exemplo n.º 20
0
def create_product_entity(link, currency, current, history, meta):
    product = Product.get_by_id(id=meta["asin"])
    if product is not None:
        return product.key
    else:
        product = Product(id=meta["asin"],
                          link=link,
                          currency=currency,
                          current=current,
                          history=history,
                          meta=meta)
        key = product.put()
        return key
Exemplo n.º 21
0
def post_add_product():
    form = AddProductForm()

    if form.validate_on_submit():
        id__ = max(all_products, key=lambda x: x.get('id_'), default={}).get('id_', 0) + 1
        product_obj = Product(id__, form.name.data, form.description.data, form.price.data,
                              secure_filename(form.image_file.data.filename))

        all_products.append(product_obj.__dict__)
        f = form.image_file.data
        f.save(os.path.join(save_img_dir, secure_filename(f.filename)))

        return redirect(url_for('products.get_all_products'))
    return render_template('add_product.html', form=form)
Exemplo n.º 22
0
 def post(self):
     json_data = request.get_json(force=True)
     if not json_data:
         return {'message': 'No input data provided'}, 400
     payload = products_schema.load(json_data)
     for item in payload:
         product = Product(product_id=item['product_id'],
                           product_price=item['product_price'],
                           product_name=item['product_name'],
                           size=item['size'])
         db.session.add(product)
     db.session.commit()
     products = Product.query.all()
     return products_schema.dump(products)
Exemplo n.º 23
0
 def save_product_info(self, productno, link, title, category):
     if self.get_product_id(productno):
         session = Session()
         insert_product = Product(ProductNo=productno,
                                  Link=link,
                                  Name=title,
                                  Category=category,
                                  TrainTest='train',
                                  Enrolltime=crawltime)
         session.add(insert_product)
         session.commit()
         session.close()
     else:
         self.update_product_info(productno, link, title, category)
Exemplo n.º 24
0
def get_product(save_db=False):
    query = """
    SELECT id, name, url FROM categories
    WHERE parent_id BETWEEN 100 AND 113;
    """
    try:
        cur.execute(query)
    except Exception as err:
        print('ERROR BY SELECT TABLE', err)

    rows = cur.fetchall()
    
    for i in rows:
        id = i[0]
        name = " ".join(i[1].strip().split()[:-1])
        url = i[2].strip()
        for page in range(1,4):
            page_url = url + "&page=" + str(page)
#             print(page_url)
            page_html = get_url(page_url)
            try:
                products_wrapper_div = page_html.find_all('div', class_='product-box-list')[0]
            except Exception as err:
                 print('ERROR BY DIV FINDALL: ', err)
            if products_wrapper_div:
                products_div = products_wrapper_div.find_all('div', class_='product-item')
                result = []
                if len(products_div) > 0:
                    for product_div in products_div:
                        product_id = None
                        title = product_div.a['title']
                        url = product_div.a['href']
                        img_url = product_div.img['src']
                        regular_price = product_div.find('span', class_='price-regular').text
                        final_price = product_div.find('span', class_='final-price').text.split()[0]
                        sale_tag = product_div.find('span', class_='sale-tag').text
                        comment = product_div.find('p', class_='review').text.split()[0] + ' review(s))'
                        if product_div.find('span', class_='rating-content'):
                            rating = product_div.find('span', class_='rating-content').find('span')['style'].split(":")[-1]
                        else:
                            rating = '0%'
                        product = Product(product_id, name, url, img_url, regular_price, final_price, sale_tag, comment, rating, id)

                        if save_db:
                            product.save_into_db()
                            print(f'SAVE {title} INTO DB')
                        result.append(product)
                else:
                    break
Exemplo n.º 25
0
def new_product():
    print "\n>> New product:\n"
    # print host
    name = raw_input("   Product name: ")
    # print name
    alias = raw_input("   Product alias: ")
    # print pwd
    pdir = raw_input("   Product dir: ")

    pd = Product.Product()
    pd.set("name", name)
    pd.set("alias", alias)
    pd.set("dir", pdir)
    executor.prod_add(pd)
    print "\n   Product created."
Exemplo n.º 26
0
def completed(payload, name, status, token):
    products = Product(context.System.apiAccessToken)
    logger.info("on-purchase-completed {}".format(request))
    logger.info("payload: {} {}".format(payload.purchaseResult,
                                        payload.productId))
    logger.info("name: {}".format(name))
    logger.info("token: {}".format(token))
    logger.info("status: {}".format(status.code == 200))
    product_name = products.productName(payload.productId)
    logger.info("Product name".format(product_name))
    if status.code == "200" and ("ACCEPTED" in payload.purchaseResult):
        return question(
            "To listen it just say - play {} ".format(product_name))
    else:
        return question("Do you want to buy another product?")
Exemplo n.º 27
0
def load_products(filename):
    """Load products from json-like file into database."""

    print "=================="
    print "loading products"

    f = open(filename)

    for line in f:
        # Each line is a dictionary containing info on a product
        p = eval(line)

        # categories are stored in double brackets for weird semi-json reasons
        categories = p['categories'][0]

        for c in categories:
            # Loop through each of the product's categories, add to the
            # categories table if it's not there

            n_results = Category.query.filter_by(cat_name=c).count()

            if n_results == 0:
                category = Category(cat_name=c)
                db.session.add(category)
                db.session.commit()

        # Pull out the product's categories again as a list of Category objects
        category_objects = Category.query.filter(
            Category.cat_name.in_(categories)).all()

        title = p.get('title')
        if title:
            title = H.unescape(title)

        description = p.get('description')
        if description:
            description = H.unescape(description)

        # Instantiate a product object
        product = Product(asin=p['asin'],
                          title=title,
                          description=description,
                          price=p.get('price'),
                          image=p.get('imUrl'),
                          categories=category_objects)

        db.session.add(product)
        db.session.commit()
 def read(self):
     products = []
     with open(self.productsFile, 'r') as f:
         reader = csv.reader(f)
         try:
             for productRow in reader:
                 products.append(Product(
                     name=productRow[0],
                     category=productRow[1],
                     price=productRow[2],
                 ))
         except csv.Error as e:
             sys.exit(
                 'file %s, line %d: %s' % (
                     self.productsFile, reader.line_num, e))
     return products
Exemplo n.º 29
0
def load_products2():
    """Load products from u.products to database"""
    print('Products')
    file = open("seed_data/u.products2")

    for row in file:

        row = row.rstrip()
        product_category, product_type, product_route, product_img = row.split(
            " = ")

        url = 'https://data.energystar.gov/resource/' + product_route

        response = requests.get(url)
        data = response.json()

        top_3_products = []  #appends the keys & values for three products
        counter = 0  #ensures only three results
        index = 0
        for product in data:  #loops over json string

            if counter < 3:  #if this is the most efficient product and there are less than three products in the list
                top_3_products.append(
                    product['brand_name'])  #add brand to product list
                top_3_products.append(product['model_number'])
                top_3_products.append('https://www.google.com/search?q=' +
                                      product['brand_name'] + '+' +
                                      product['model_number'])
                counter += 1  ##add one to the counter

                product_brand = top_3_products[0]
                product_model = top_3_products[1]
                product_link = top_3_products[2]

                product = Product(product_category=product_category,
                                  product_type=product_type,
                                  product_brand=product_brand,
                                  product_model=product_model,
                                  product_link=product_link,
                                  product_img=product_img)

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

            index += 1

    db.session.commit()
Exemplo n.º 30
0
    def create_product(self, to_add):
        session = self.Session()

        try:
            product = Product(product_name=to_add['productName'],
                              description=to_add['description'],
                              price=to_add['price'])
            self.add_object(product)
            session.commit()

            return product.to_json()
        except Exception as e:
            logging.error('*** Exception in create_product: %s' % e)
            session.rollback()
            raise
        finally:
            session.close()