Exemplo n.º 1
0
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 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
Exemplo n.º 3
0
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()]
Exemplo n.º 4
0
    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
Exemplo n.º 5
0
 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])
Exemplo n.º 6
0
Arquivo: api.py Projeto: Vakeros/p5
    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")
Exemplo n.º 7
0
    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
Exemplo n.º 8
0
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
Exemplo n.º 9
0
 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
Exemplo n.º 10
0
    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"])
Exemplo n.º 11
0
 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
Exemplo n.º 12
0
    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)
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
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)
Exemplo n.º 15
0
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
Exemplo n.º 16
0
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
Exemplo n.º 17
0
 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
Exemplo n.º 18
0
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>"
Exemplo n.º 19
0
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
Exemplo n.º 20
0
    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
Exemplo n.º 21
0
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  
Exemplo n.º 22
0
from products import Product
from scraper import *
import certificate, time

new_price = Product()
n = int(input("1. Amazon\n2. Flipkart\nenter your choice: "))

url = input("enter the url of the product you want to track -\n")

if n == 1:
    while (True):
        Amazon().findPrice(url, new_price)
        time.sleep(600)
elif n == 2:
    while (True):
        Flipkart().findPrice(url, new_price)
        #time.sleep(600)
Exemplo n.º 23
0
                           type=str,
                           required=True,
                           help='Item Code',
                           location='form')
basket_parser.add_argument('qty',
                           type=int,
                           required=True,
                           help='Product Qty',
                           location='form')
product_parser.add_argument('status',
                            type=str,
                            required=True,
                            help='Item Status',
                            location='form')

product = Product(mysql)
basket = Basket(mysql)


@pns.route('/')
class ProductList(Resource):
    '''Shows a list of all Products, and lets you to add new Products'''
    @pns.doc('list_all_product')
    def get(self):
        '''List all Products'''
        return product.get_all()

    @api.doc(parser=product_parser)
    def post(self):
        '''Add New Product'''
        args = product_parser.parse_args()
Exemplo n.º 24
0
from store import Store
from products import Product

Coops = Store(name="Coops")

skates = Product('Skates', 800, 'Hockey')
stick = Product('Stick', 300, 'Hockey')

Coops.add_product(skates)
Coops.add_product(stick)

skates.print_info()
stick.print_info()

# Coops.sell_product(0)

Coops.set_clearance('Hockey', .50)
print('*' * 50)
skates.print_info()
stick.print_info()
Exemplo n.º 25
0
 def get_products(self):
     prod1 = self._combobox_one.get()
     prod2 = self._combobox_two.get()
     self._product = Product(prod1=prod1, prod2=prod2)
     return self._product.locate_product()
Exemplo n.º 26
0
 def insert_products(self):
     Product(self.categories_list).insert_product_values(True)
Exemplo n.º 27
0
    def total(self):
        total = 0
        for product in self.products:
            total += product.total_price()
        return "Your total after tax is ${}.".format(total)

    def most_expensive(self):
        prices = []
        for product in self.products:
            prices.append(product.base_price)
        expensive_item = max(prices)
        return "The most expensive item is {} at ${}".format(
            product.name, expensive_item)


train = Product('Thomas the Tank Engine', 15, 0.13)
car = Product('Lightning McQueen', 25, 0.13)
bus = Product('The Magic School Bus', 20, 0.13)
shopping_cart = ShoppingCart()

shopping_cart.add_item(train)
shopping_cart.add_item(car)
shopping_cart.add_item(bus)
shopping_cart.add_item(car)
shopping_cart.add_item(car)

shopping_cart.rem_item(car)

print(shopping_cart)
print(shopping_cart.subtotal())
print(shopping_cart.total())
Exemplo n.º 28
0
from products import Product
from store import Store

num_args = len(sys.argv)
if num_args == 1:
    user = User(100)
elif num_args == 2:
    user = User(int(sys.argv[1]))
else:
    print("Usage: store.py [money]")
    sys.exit(1)

departments = {
    23:
    Department(23, "Groceries", [
        Product("Bananas", 0.60),
        Product("Avos", 2.60),
        Product("Watermelon", 1.60)
    ]),
    9:
    Department(9, "Books", [
        Product("Game of Thrones", 10.60),
        Product("Working in Public", 12.60),
        Product("Watermelon Chronicles", 1.60)
    ]),
    13:
    Department(13, "Electronics", [
        Product("Samsung 4k TV", 300.60),
        Product("Iphone SE", 2000.60),
        Product("Pixel 4a", 1000.60)
    ]),
from products import Product
from shopping_cart import Shopping_Cart

#Instantiate each Product class.
computer = Product('Computer', 1500, 'standard')
television = Product('Television', 2500, 'standard')
oculus_rift = Product('Oculus Rift', 999, 'imported')
iPhone = Product('Apple iPhone', 800, 'imported')
mouse_pad = Product('Mouse Pad', 5, 'tax-exempt')

#Instantiate each Shopping_Cart class.
bobs_cart = Shopping_Cart('Bob')

#Adding items to cart.
print(bobs_cart.add_to_cart(computer, 1))
print(bobs_cart.add_to_cart(television, 1))
print(bobs_cart.add_to_cart(oculus_rift, 1))
print(bobs_cart.add_to_cart(iPhone, 3))
print(bobs_cart.add_to_cart(mouse_pad, 1))
print()

print(bobs_cart.most_expensive_product_in_cart())
print()

#Display all items in bobs_cart.
bobs_cart.display_total()
print('\n\n')

#Instantiate each Shopping_Cart class.
billys_cart = Shopping_Cart('Billy')
Exemplo n.º 30
0
        self.name = name
        self.departments = departments

    def __str__(self):
        return f"Wecome to the Quarantine store! Have a nice shopping experience!"

    def print_departments(self):
        for id in self.departments:
            print(self.departments[id])
        print()


departments = {
    23:
    Department(23, "Groceries", [
        Product("Bananas", 0.60),
        Product("Avocados", 2),
        Product("Watermelons", 6)
    ]),
    9:
    Department(9, "Books", [
        Product("Game of Thrones", 10),
        Product("Fahrenheit 451", 15),
        Product("Working in Public", 25)
    ]),
    13:
    Department(13, "Electronics", [
        Product("Samsung 4K TV", 300),
        Product("iPhone SE", 400),
        Product("Pixel 4A", 100)
    ]),