def __init__(self, master, *args, **kwargs): tk.Frame.__init__(self, master, *args, **kwargs) self.master = master self._product = Product() self._list_products = self._product.list_all_products() self._prod1 = tk.StringVar(value=self._list_products[0]) self._prod2 = tk.StringVar(value=self._list_products[1])
def display_favorite(self): system("cls") all_fav = Favourites.display_all_favourite_product() element_to_search = {} if all_fav != []: for element in all_fav: element_to_search[element[0]] = element[1] C_EMPTY.append( Product.display_product(["name_product"], "id_product", element[0])[0][0]) C_EMPTY.append(MAIN_MENU) C_EMPTY.append(SUPRESS) qst_all_fav = Question(QUESTIONER, Q5, clean=1).answer if qst_all_fav != SUPRESS and qst_all_fav != MAIN_MENU: favourite_prod = Product.display_product(["id_product"], "name_product", qst_all_fav)[0][0] Favourites.display_favourite_product( str(favourite_prod), str(element_to_search[favourite_prod])) all_fav.clear() C_EMPTY.clear() elif qst_all_fav == SUPRESS: Favourites.suppress_all() all_fav.clear() C_EMPTY.clear() return MAIN_MENU elif qst_all_fav == MAIN_MENU: C_EMPTY.clear() return MAIN_MENU else: Question(display(150, "=", NO_FAV_PRODUCT, 1, "|", "left"), clean=1) return MAIN_MENU
def put_product(): RESOURCE = '/Products/' try: guid = str(uuid.uuid4()) product = Product(None) product.Description = 'New product from API' product.SearchName = 'New API product' product.Comment = 'This product is created by the Python API client with id: ' + guid product.Price = 12.50 client = ApiClient(URI, HEADERS, USERNAME, PASSWORD) response = client.PUT(RESOURCE + guid, product.json()) if response.status_code == 200 and response.is_json: pprint.pprint(response.json) product = Product(response.json) print("{0:38} {1:40} {2:20} {3}".format(product.id, product.Description[:40], product.SearchName[:20], product.Price)) else: print("response error: %d - %s" % (response.status_code, response.text)) except ValueError: print("Unexpected data: ", response.text) except: print("Unexpected error:", sys.exc_info()[0])
def show_product_info(product_obj: Product): '''disply a product's info''' print("PRODUCT DATA") print("Name: {:s}".format(product_obj.name)) print("Price: ${:,.2f}".format(product_obj.price)) print("Discount Percent: {:d}%".format(product_obj.discountPercent)) print("Discount Amount: {:.2f}".format( product_obj.getDiscountAmount())) print("Discount Price: {:.2f}".format( product_obj.getDiscountPrice())) print()
def multi_process_handle(products, row): _, record = row print('Iteration :', _) values_list = record.values.tolist() first = values_list[:len(PRODUCT_MAP_LIST)] second = values_list[len(PRODUCT_MAP_LIST):] f_prod = Product(first, 2, True) s_prod = Product(second, 3, True) # print(prod) task = optimizer(products + [f_prod, s_prod]) return task
def add_product(self, user_id): temp = self.get_info(user_id, 'temp') name = temp[0] quantity = temp[1] cost = quantity * Product.get_price(name) self.data[str(user_id)]['products'].append( [name, quantity, cost, f'{datetime.now()}']) self.save() self.update_user(user_id, 'temp', []) self.update_user(user_id, 'status', 0) Product.update_product(name, quantity)
def show_product(id): try: product = Product(id=id) except Exception: return "<h1>Not found</h1>", 404 if request.method == "DELETE": product.delete() return "Deleted" return flask.render_template("product.html", product=product)
def answer(context, bot): user_id = context.message.chat_id msg_text = context.message.text status = DB.get_info(user_id, 'status') if status == 1 and msg_text.isdigit(): msg_text = int(msg_text) DB.update_user(user_id, 'temp', msg_text) if pr.get_quantity(DB.get_info(user_id, 'temp')[0]) >= msg_text: data = DB.get_info(user_id, 'temp')[0] text = tx.get_text('status_1').format( data, msg_text, msg_text * pr.get_price(data)) bot.bot.send_message(user_id, text, reply_markup=final_question()) DB.update_user(user_id, 'status', 2)
def show_products(): if request.method == "POST": print(request.form) # todo: надо убедиться, что в форме корректные данные # validation product = Product(name=request.form['name'], category=request.form['category'], price=float(request.form['price']), quantity=int(request.form['quantity'])) product.save() return flask.redirect("/", code=404) else: return "<h1>Products page</h1>"
def ans_pr(update, bot): query = update.callback_query user_id = query.message.chat_id msg_id = query.message.message_id status = DB.get_info(user_id, 'status') if query.data in pr.get_products_name() and status == 0: DB.update_user(user_id, 'temp', query.data) text = "Продукт успешно выбран" bot.bot.edit_message_text(chat_id=user_id, message_id=msg_id, text=text, reply_markup=product_names(query.data)) DB.update_user(user_id, 'status', 1) text = tx.get_text('pr_ch').format( DB.get_info(user_id, 'temp')[0], pr.get_quantity(query.data)) bot.bot.send_message(user_id, text)
def test_should_query_webdriver(self): import os # import pandas as pd from products import Product ProductDatabase.clear_database() filename = 'test.json' extractor = PageExtractor('submarino') products_list = extractor.query_webdriver("goblet of fire") products = [Product(item_attrs) for item_attrs in products_list] extractor.store_products_on_json(products, filename) # import pdb; pdb.set_trace() filtered_products = ProductDatabase.filter(price__gte=700, price__lt=1000) extractor.store_products_on_json(filtered_products, 'test_filtered.json') # df = pd.DataFrame({ # 'name': [prod.name for prod in filtered_products], # 'price': [prod.price for prod in filtered_products] # }) assert os.path.exists(filename) == True # We cant check it like this since the add_product on ProductDatabase checks whether the product was already inserted # assert len(products_list) == ProductDatabase.get_products_total() assert ProductDatabase.get_products_total() != 0
def __get_products(): """get data from openfoodfact API""" i = 0 for categories_values in API.categories: print("Récupération des produits " + str(i + 1) + " / " + str(len(API.categories))) for page in range(1, PAGE_COUNT + 1): data = requests.get(categories_values["url"] + "/" + str(page) + ".json") data_json = data.json() products_data_json = data_json["products"] for prod in products_data_json: product = Product([ prod.get("product_name_fr", ""), prod.get("url"), prod.get("stores", ""), prod.get("nutriscore_grade", "X"), i + 1 ]) if prod.get("product_name_fr", "") != "" \ and prod.get("generic_name_fr", "") != "unknown" \ and prod.get("nutriscore_grade", "X") != "X" \ and prod.get("stores", "") != "": API.products.append(product) i += 1 print("Done")
def retrieve_products_from_query(self, query: str) -> list: ''' Returns a list of Product objects from the extracted data got when searching for the given query in the instance e-commerce website ''' parsed_html = self.retrieve_html_parsed_from_query(query) items_dicts_list = self.get_info_list_about_products(parsed_html) products = [Product(item_attrs) for item_attrs in items_dicts_list] return products
def populate_products_database_from_json_and_return_list(): ''' Gets all the data from json file and create Product objects to populate ProrductDatabase ''' data_loaded = get_data_from_json() products_list = [] for data in data_loaded: print(data) products_list.append(Product(data)) return products_list
def load_products_from_json(filename = 'product_data.json'): with open(filename) as pdf: products_from_file = json.load(pdf) print(f"PRODUCTS {products_from_file}") product_list = [] for product_dict in products_from_file: product = Product(product_dict['name'], Decimal(product_dict['cost']), product_dict['description']) product_list.append(product) return product_list
def products(self): results = [] s = offer_product_prices_table.select(offer_product_prices_table.c.offer_id == self.offer.id) rs = s.execute() for row in rs: product = Product.find_by_id(row['product_id']) results.append(dict(offer_id=row['offer_id'], name=product.name, description=product.description)) return results
def show_cart(): """List items in shopping cart, prices, and total""" total_price = 0 cart_list = [Product.get_by_id(id) for id in session['cart']] for product in cart_list: total_price += product.price return render_template("cart.html", total=total_price, products=cart_list)
def test_take_purchase(self): product = Product("alice in wonderland", Decimal("10.00"), "children's book") quantity = 2 purchase = take_purchase(product, quantity) self.assertEqual(purchase.product_name, product.name) self.assertEqual(purchase.cost, product.cost) self.assertEqual(purchase.qty, quantity)
def from_dict(self, orders): for order in orders: products_dict = dict() for product in order["products"]: product_order = ProductOrder( Product(product["name"], product["price"], product["iva"], product["unit"]), product["amount"]) products_dict[product["reference"]] = product_order self.orders[order["id"]] = Order(products_dict, order["client"])
def populate_list_for_test(): test_list = [] test_list.append(Product({ 'name': 'Product 1', 'price': 35 })) test_list.append(Product({ 'name': 'Item 1', 'price': 50 })) test_list.append(Product({ 'name': None, 'price': 42 })) test_list.append(Product({ 'name': 'Item 2', 'price': None })) return test_list
def get_products_from_json(cls, file_name: str) -> List[Product]: ''' Return a list of products extracted from json file with file_name ''' import json products = [] with open(file_name) as data_file: data_loaded = json.load(data_file) for data in data_loaded: products.append(Product(data)) return products
def get_info_dict_for_product(item) -> dict: ''' Return a dictionary with main information about the product item passed ''' price_extractor = '{}[class*="{}"]'.format(*get_extractor_tag_and_class_tuple('magazine_luiza', 'price')) link_extractor = '{}[class*="{}"]'.format(*get_extractor_tag_and_class_tuple('magazine_luiza', 'link')) name_extractor = '{}[class*="{}"]'.format(*get_extractor_tag_and_class_tuple('magazine_luiza', 'name')) image_extractor = '{}[class*="{}"]'.format(*get_extractor_tag_and_class_tuple('magazine_luiza', 'image')) # price_extractor = '{}[class*="{}"]'.format(get_extractor_tag_and_class_tuple('magazine_luiza', 'price')) # import pdb; pdb.set_trace() price_span = item.select(price_extractor) price_span = price_span[0] if len(price_span) else None # product_anchor = item.select(link_extractor) # product_anchor = product_anchor[0] if len(product_anchor) else None # image = product_anchor.find('img') img_tag, img_class = get_extractor_tag_and_class_tuple('magazine_luiza', 'image') image = item.find(img_tag, class_=img_class) name_tag, name_class = get_extractor_tag_and_class_tuple('magazine_luiza', 'name') name_h2 = item.find(name_tag, class_=name_class) link_tag, link_class = get_extractor_tag_and_class_tuple('magazine_luiza', 'link') link = item.find(link_tag, class_=link_class) price_tag, price_class = get_extractor_tag_and_class_tuple('magazine_luiza', 'price') price_str = item.find(price_tag, class_=price_class) # name_h2 = item.find("h2", class_="TitleUI-bwhjk3-15 khKJTM TitleH2-sc-1wh9e1x-1 gYIWNc") # name_h2 = item.select(name_extractor) # name_h2 = name_h2[0] if len(name_h2) else None name = name_h2.get_text() if name_h2 else 'SEM NOME' price_str = price_span.get_text() if price_span else 'SEM PRECO' link_url = link.get('href') if link else 'SEM LINK' image_url = image.get('src') if image else 'SEM IMAGEM' if price_span: # Value is received like this: 'R$ 1.498,00' price_str = price_span.get_text() price = convert_BRL_currency_to_float(price_str[3:]) else: price_str = 'SEM PRECO' price = None info_dict = { 'name': name, 'price_str': price_str, 'price': price, 'link': link_url, 'image_url': image_url } Product(info_dict) return info_dict
def test_should_query_for(self): retriever = DataRetriever(['submarino']) products_dicts = retriever.query_for('iphone') # import pdb; pdb.set_trace() products = [Product(item_attrs) for item_attrs in products_dicts] DataRetriever.store_products_on_json(products, 'test.json') # import pdb; pdb.set_trace() filtered_products = ProductDatabase.filter(price__gte=3000, price__lt=4000) DataRetriever.store_products_on_json(filtered_products, 'test_filtered.json') assert type(products_dicts) == list assert type(products_dicts[0]) == dict
def main(): print("The Product Viewer Program") print() # a tuple of Product objects products = (Product("Stanley 13 Ounce Wood Hammer", 12.99, 62), Product('National Hardware 3/4" Wire Nails', 5.06, 0), Product("Economy Duct Tape, 60 Yds, Silver", 7.24, 0)) list_products(products) while True: number = int(input("Enter product number: ")) print() selected_product = products[number - 1] show_product_info(selected_product) choice = input("View another product? (y/n): ") print() if choice.lower() != "y": print("Bye!") break
def search_product_to_replace(self): #Function to find products by name correct_product = True while correct_product: product_to_replace = Question(display(150, "=", REPLACE_PROD, 2, "|", "left"), clean=1).answer if len(product_to_replace) >= 3: prod_find = Product.display_product( ["name_product, nutrition_grades_product"], 'name_product', "%" + product_to_replace + "%") if prod_find != []: for element in prod_find: C_EMPTY.append(element[0] + " (" + element[1] + ")") C_EMPTY.append(MAIN_MENU) favourite_prod = Question(QUESTIONER, Q5, clean=1).answer if favourite_prod != MAIN_MENU: choiced_product = Product.display_product( ["*"], "name_product", favourite_prod[0:-4])[0] self.display_details(choiced_product) ids = self.ask_found_better(str(choiced_product[2])) if ids != MAIN_MENU: rec = self.ask_add_favourite( ids, choiced_product[0]) return MAIN_MENU else: return MAIN_MENU else: return MAIN_MENU else: no_product = Question(QUESTIONER, Q7, clean=1).answer if no_product == "Réessayer.": continue else: return no_product else: system("cls") input(display(150, "=", SEARCHING_RULE, 2, "|"))
def search_products_like_category(self): #Function to find products by category cat_prod_dict = {} category_to_check = self.answer.lower().replace(".", "") category_id = Categories.read_column_sql( "id", f"WHERE name='{category_to_check}'") cat_products = Product.display_product( ["name_product", "id_product", "nutrition_grades_product"], 'category_ID', category_id[0]) product_and_grade = [] for element in cat_products: cat_prod_dict[element[0]] = [element[1], element[2]] product_and_grade.append(element[0] + " (" + element[2] + ")") C_EMPTY.append(product_and_grade[-1]) first_question = Question(QUESTIONER, Q3_1, clean=1).answer choiced_product = Product.display_product( ["*"], "id_product", f"{cat_prod_dict[first_question[0:-4]][0]}")[0] C_EMPTY.clear() self.display_details(choiced_product) ids = self.ask_found_better(category_id) if ids != MAIN_MENU: self.ask_add_favourite(ids, choiced_product[0]) return MAIN_MENU
def AddProduct(): try: data = request.data data = json.loads(data) product_id = data['product_id'] product_name = data['product_name'] product_details = data['product_details'] product_price = data['product_price'] date = datetime.datetime.now() product_images = [] product_category = data['product_category'] product_keywords = data['product_keywords'] product_quantity = data['product_quantity'] product_rating = data['product_rating'] product = Product(product_id = product_id, product_name = product_name, product_details = product_details, product_price = product_price, date = date, product_images = product_images, product_category = product_category, product_keywords = product_keywords, product_quantity = product_quantity, product_rating = product_rating) if product.Save(): return 'Done',200 return 'Failed', 400 except Exception as e: print e logger.debug('Exception in adding products') return str(e), 500
def ask_found_better(self, category_id): #Function to suggest finding a better product. better_prod = Question(QUESTIONER, Q6, clean=1).answer if better_prod == "Oui.": C_EMPTY.clear() prod_search = Product.display_product( ["name_product", "id_product", "nutrition_grades_product"], "category_ID", category_id[0], order_by="nutrition_grades_product", numlimit="5") product_and_grade = [] for found_prod in prod_search: product_and_grade.append(found_prod[0] + " (" + found_prod[2] + ")") C_EMPTY.append(product_and_grade[-1]) fav_prod = Question(QUESTIONER, Q6_1, clean=1).answer fav_prod_details = Product.display_product(["*"], "name_product", fav_prod[0:-4])[0] self.display_details(fav_prod_details) C_EMPTY.clear() return fav_prod_details[0] else: return MAIN_MENU
def fetch_produtos(url, category, ingredient): wholehtml = open_URL(url) print '\n[+] Returned Products' soup = BeautifulSoup(wholehtml) prodhtml = soup.findAll("div", "boxProduct") products = [] for html in prodhtml: desc = html.findChild("h3").text img = get_URL(html.findChild("img").get('src')) id_ = get_id(html.findChild("footer").get('id')) produto = Product(ProductId('pda', id_), desc, category, None, img, ingredient) products.append(produto) print '[.]\t\t Product: ' + desc return products
def test_should_store_products_on_json(self): import os retriever = DataRetriever(['submarino']) products_dicts = retriever.query_for('iphone') file_name1 = 'test2.json' if os.path.exists(file_name1): os.remove(file_name1) DataRetriever.store_products_on_json(products_dicts, file_name1) assert os.path.exists(file_name1) == True file_name2 = 'test3.json' if os.path.exists(file_name2): os.remove(file_name2) products = [Product(item_attrs) for item_attrs in products_dicts] DataRetriever.store_products_on_json(products, file_name2) assert os.path.exists(file_name2) == True
def create_test_data(): db.drop_all() db.create_all() milch = Product(name='Milch', amount=5, required_amount=10) burger = Product(name='Burger', amount=50, required_amount=40) db.session.add(milch) db.session.add(burger) db.session.commit() return [milch.to_dict(), burger.to_dict()]