Beispiel #1
0
def new_product():
    barcode = cgi.escape(request.form['data'])
    compare(barcode)

    if comparator.barcodeExist():
        if cartlist.checkIfAlreadyInList(barcode):
            product = cartlist.getProduct(barcode)

            # If is in cart, add one more to list
            product.oneMore()
            cartlist.addToTotal(product.getPrice())
        else:
            newproduct = products.Product(barcode, comparator.getDescription(), comparator.getPrice())
            cartlist.addProduct(newproduct)

        # Set all the variables to be passed
        key = barcode
        quantity = cartlist.getProduct(barcode).getQuantity()
        producttotal = quantity * float(cartlist.getProduct(barcode).getPrice())
        description = cartlist.getProduct(barcode).getDescription()
        total = round(cartlist.getTotal(), 2) # Round 2 digits

        pusher.trigger('data', 'new_product', {
            # Push them to server
            'key': key,
            'description': description,
            'quantity': quantity,
            'producttotal': producttotal,
            'total': total
        })

        # Clear database results to fetch more next time
        comparator.clearResults()
        return "great success!"
Beispiel #2
0
def process_user_input(choice):
    """Chooses what to do based on User input"""
    if choice == '1':
        # Get User input for product details
        prod_name = get_new_name()
        prod_price = get_new_price()
        prod_desc = get_new_description()

        # Instantiate the product object
        prod_obj = products.Product()
        prod_obj.create_product(prod_name, prod_price, prod_desc)
        return False
    elif choice == '2':
        prod_obj = products.Product()
        prod_obj.list_products()
        return False
    elif choice == '3':
        # User exits program
        print 'Goodbye!'
        return True
    else:
        print '!!! Invalid choice !!!'
        print '!!!  CHOOSE AGAIN  !!!'
        return False
Beispiel #3
0
import store
import products

shinok = store.Store(name="Shinok")
kolbasa = products.Product(name="kolbasa", price=50, category="meat")
hleb = products.Product(name="hleb", price=10, category="hleb")
morkva = products.Product(name="morkva", price=5, category="vegies")

shinok.add_product(kolbasa).add_product(hleb).add_product(morkva)

shinok.sell_product(1).set_clearance(50).sell_product(0)
Beispiel #4
0
    " & ", " &", "& ", ", ", " ,", " -", "- ", ";", ":", "!", "(", ")"
    "\""
]
key_add_words = ["купить", "распродажа"]

xmlPath = "https://gunsto.prom.ua/yandex_market.xml?hash_tag=b9ad6ea71fccc0f742251582148b0f12&sales_notes=&product_ids=&label_ids=3204078&exclude_fields=&html_description=0&yandex_cpa=&process_presence_sure=&export_lang=ru&group_ids="


def has_cyrillic(text):
    return bool(re.search('[а-яА-Я]', text))


if __name__ == '__main__':
    # productList = products.XmlPromProductService.get_products(xmlPath)
    productList = [
        products.Product("32431414", 'Пули H&N Silver Point (0.75г, 500 шт)',
                         'Пуля для пневматического оружия')
    ]
    analyz = pymorphy2.MorphAnalyzer()
    wordParse = analyz.parse("пневматическая винтовка")[0]
    dich2 = wordParse.inflect({'sing', 'accs'}).word

    for product in productList:
        product_key_words = set()
        product_name = product.name.lower()
        for bad in bad_entries:
            product_name = product_name.replace(bad, " ")

        product_name = re.sub(' +', ' ', product_name)
        product_group_name = product.group_name.lower()

        group_name_words_arr = product_group_name.split(" ")
Beispiel #5
0
def get_prices(name):
    keywords = name.replace(" ", "%20")
    result = scrape(keywords)

    if len(result["hits"]) == 0:
        raise errors.NoProductsFound

    product_url = result["hits"][0]["url"]

    apiurl = f"https://stockx.com/api/products/{product_url}?includes=market,360&currency=USD&country=US"

    header = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "accept-encoding": "gzip, deflate",
        "referer": f"https://stockx.com/{product_url}",
    }

    response = requests.get(apiurl, verify=True, headers=header)
    if response.status_code == 403:
        raise errors.SiteUnreachable

    response = response.json()
    general = response["Product"]

    product = products.Product(
        title=general["title"],
        url=f"https://stockx.com/{general['urlKey']}",
        thumbnail=general["media"]["thumbUrl"],
        color=0x099F5F,
        footer_text="StockX",
        footer_image=
        "https://cdn.discordapp.com/attachments/734938642790744097/771078700178866226/stockx.png",
        processing_fee=3.0,
        asks_and_bids=True,
        category=general["contentGroup"],
    )
    product.add_seller_fee(9.5)
    product.add_seller_fee(9.0)
    product.add_seller_fee(8.5)
    product.add_seller_fee(8.0)

    for child in general["children"]:
        current_size = general["children"][child]
        if current_size["shoeSize"] == "15":
            break

        product.set_prices(
            size=current_size["shoeSize"],
            ask=current_size["market"]["lowestAsk"],
            bid=current_size["market"]["highestBid"],
        )

    if product.get_category() == "sneakers":
        if "styleId" in general:
            product.set_sku(general["styleId"])
        if "retailPrice" in general:
            product.set_retail_price(general["retailPrice"])
    elif product.get_category() == "streetwear-clothing":
        retail_price = next(
            (item for item in general["traits"] if item["name"] == "Retail"),
            None)
        if retail_price:
            product.set_retail_price(retail_price["value"])
    elif (product.get_category() == "collectibles"
          or product.get_category() == "handbags"):
        retail_price = next(
            (item for item in general["traits"] if item["name"] == "Retail"),
            None)
        product.set_one_size()
        if retail_price:
            product.set_retail_price(retail_price["value"])
    else:
        raise errors.ProductNotSupported

    return product
Beispiel #6
0
import store
import products

store_A = store.Store("Store_A")
banana = products.Product("Banana", 1.99, "Fruits", 1)
apple = products.Product("Apple", 0.99, "Fruits", 2)
burger = products.Product("Burger", 5.99, "American", 3)

store_A.add_product(banana).add_product(apple).add_product(burger)
store_A.print_info()

store_A.sell_product(1)
store_A.print_info()

store_A.inflation(0.10)
store_A.print_info()

store_A.set_clearance("Fruits", 0.5)
store_A.print_info()
Beispiel #7
0
def get_prices(name):
    keywords = name.replace(" ", "%20")
    results = scrape(keywords)

    if len(results["hits"]) == 0:
        raise errors.NoProductsFound

    header = {
        "accept-encoding":
        "gzip, deflate, br",
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36",
    }

    results = results["hits"][0]

    apiurl_prices = f"https://www.goat.com/web-api/v1/product_variants/buy_bar_data?productTemplateId={results['product_template_id']}"
    apiurl_general = (
        f"https://www.goat.com/_next/data/dxe0D_HRq8UvcoQmr76-N/en-US/sneakers/{results['slug']}.json?pageSlug=sneakers&productSlug={results['slug']}"
    )

    options = requests.get(apiurl_prices, verify=True, headers=header)
    general = requests.get(apiurl_general, verify=True, headers=header)

    options = options.json()
    general = general.json()["pageProps"]["productTemplate"]

    product = products.Product(
        title=general['name'],
        url=f"https://www.goat.com/sneakers/{general['slug']}",
        thumbnail=general["gridPictureUrl"],
        color=0xFFFFFE,
        footer_text="Goat",
        footer_image=
        "https://cdn.discordapp.com/attachments/734938642790744097/771077292881477632/goat.png",
        processing_fee=2.9,
        asks_and_bids=False,
    )
    product.add_seller_fee(9.5)

    for size in options:
        if (size["boxCondition"] == "good_condition"
                and size["shoeCondition"] == "new_no_defects"):
            if size["sizeOption"]["value"] == 15:
                break
            if size["stockStatus"] == "not_in_stock":
                lowest_price = 0
            else:
                lowest_price = int(size["lowestPriceCents"]["amountUsdCents"] /
                                   100)

            product.set_prices(size["sizeOption"]["presentation"],
                               lowest_price)

    if "sku" in general:
        product.set_sku(general["sku"])

    if "localizedSpecialDisplayPriceCents" in general:
        price = int(
            general["localizedSpecialDisplayPriceCents"]["amountUsdCents"] /
            100)
        if price != 0:
            product.set_retail_price(price)

    return product
Beispiel #8
0
def get_prices(name):
    header = {
        "accept":
        "application/json",
        "content-type":
        "application/json",
        "accept-encoding":
        "gzip, deflate",
        "user-agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    }

    data = {
        "operationId": "sg-front/cached-a41eba558ae6325f072164477a24d3c2",
        "variables": {
            "categorySlug": "",
            "initialSearchQuery": name,
            "initialSort": "RELEVANCE",
            "includeUnavailableProducts": None,
            "filteringOnCategory": False,
            "filteringOnBrand": False,
            "filteringOnMensSizes": False,
            "filteringOnKidsSizes": False,
            "filteringOnWomensSizes": False,
            "filteringOnApparelSizes": False,
            "filteringOnGender": False,
            "filteringOnColor": False,
            "filteringOnPriceRange": False,
        },
        "locale": "USA_USD",
    }

    r = requests.post(
        "https://graphql.stadiumgoods.com/graphql",
        headers=header,
        verify=True,
        json=data,
    )

    data = r.json()
    if len(data["data"]["configurableProducts"]["edges"]) == 0:
        raise errors.NoProductsFound

    data = data["data"]["configurableProducts"]["edges"][0]["node"]

    product = products.Product(
        title=f"{data['name']} {data['nickname']}",
        url=data["pdpUrl"],
        thumbnail=data["smallImage"]["url"],
        color=0xFFA500,
        footer_text="Stadium Goods",
        footer_image=
        "https://media.discordapp.net/attachments/734938642790744097/859866121033089064/sg.jpg",
        processing_fee=0.0,
        asks_and_bids=False,
    )
    product.add_seller_fee(20.0)

    product.set_sku(data["manufacturerSku"].replace(" ", "-"))

    header = {
        "user-agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }

    response = requests.get(data["pdpUrl"], headers=header, verify=True)
    soup = BeautifulSoup(response.content, "html.parser")
    all_sizes = soup.find("div", {
        "class": "product-sizes__options"
    }).find_all("span", {"class": "product-sizes__detail"})
    prices = []
    for option in all_sizes:
        size = int_or_float(
            option.find("span", {
                "class": "product-sizes__size"
            }).text.replace("Y", "").replace("W", "").strip("\n"))
        if size == 15:
            break
        price = option.find("span", {
            "class": "product-sizes__price"
        }).text.strip("\n")
        if "Notify me" in price:
            price = 0
        else:
            price = price.replace(".00", "")
            price = int(price.strip("$"))
        prices.append((size, price))

    prices.sort()

    for price in prices:
        size = str(price[0])
        price = price[1]

        product.set_prices(size, price)

    return product
Beispiel #9
0
import products
import store

joeys = store.Store("Joey's")

pizza = products.Product("pizza", 8, "junk food")
kiwi = products.Product("kiwi", .75, "fruit")
root_beer = products.Product("root beer", 2, "beverage")

joeys.add_product(pizza)
joeys.add_product(kiwi)
joeys.add_product(root_beer)

joeys.print_products()

print("Inflated:", joeys.inflation(.05).print_products())

print("Clearance", joeys.set_clearance(.075).print_products())

joeys.sell_product(pizza.id).print_products()