Пример #1
0
    def process(self, filename, delimiter, target_fields):
        processed, delimiter = 0, delimiter or ','
        target_fields = [
            getattr(Product, f) for f in target_fields.split(delimiter)
        ]
        statuses = {-1: 0, 0: 0, 1: 0}
        with open(filename) as f:
            for row in csv.DictReader(f, delimiter=delimiter):
                processed += 1
                if processed % 50000 == 0:
                    logger.info('Processed: {}, statuses: {}'.format(
                        processed, statuses))

                row['active'] = {'False': False, 'True': True}[row['active']]
                try:
                    is_new, product = Product.load_from_source(row)
                    if is_new:
                        logger.error('Product is new! id: {}'.format(
                            row['id']))
                    else:
                        statuses[product.active -
                                 Product.get(id=product.id).active] += 1
                        product.save(only=target_fields)
                except Exception as e:
                    logger.error(e)
            logger.info('Processed: {}, statuses: {}'.format(
                processed, statuses))
Пример #2
0
    def get(self, request):
        cart = request.session.get('cart')
        categories = Category.getAllCategory()
        products = Product.getAllProduct().order_by('-id')

        if request.GET.get('id'):
            filterProductById = Product.objects.get(
                id=int(request.GET.get('id')))
            return render(request, 'productDetail.html', {
                "product": filterProductById,
                "categories": categories
            })

        if not cart:
            request.session['cart'] = {}

        if request.GET.get('category_id'):
            filterProduct = Product.getProductByFilter(
                request.GET['category_id'])
            return render(request, 'home.html', {
                "products": filterProduct,
                "categories": categories
            })

        return render(request, 'home.html', {
            "products": products,
            "categories": categories
        })
Пример #3
0
def addproduct(request):
    product_name = request.POST.get("name")
    product_price = request.POST.get("price")
    new_product = Product(label=product_name, price=float(product_price))
    new_product.save()

    context = {}
    context["products"] = Product.objects.all()
    return render(request, "store/products.html", context)
Пример #4
0
class TestStoreUrls(TestCase):
    """Test Store app urls"""
    def setUp(self):
        # Create a product with its image file
        self.product_data = {
            'name': 'test product name',
            'description': 'test product description',
            'base_price': 49.99,
        }
        with open(f'{settings.BASE_DIR}/store/tests/_test_file_1.png',
                  'rb') as image_file:
            image = ImageFile(image_file)

            self.product = Product(**self.product_data)
            self.product.image.save(new_image_path(self.product, image.name),
                                    image)
            self.product.save()

    def tearDown(self):
        # Remove file in directory after tests
        # Comment out to check path & file creation
        product_path = f'media/products/{self.product.sku}'
        shutil.rmtree(product_path)

    def test_store_landing_url(self):
        """Test Store landing page url and used template"""

        store_page = self.client.get("/store/")
        self.assertEqual(store_page.status_code, 200)
        self.assertTemplateUsed(store_page, 'store/store.html')

    def test_product_details_url(self):
        """Test Store's product details url and used template"""

        product_page = self.client.get(f'/store/{self.product.id}/')
        self.assertEqual(product_page.status_code, 200)
        self.assertTemplateUsed(product_page, 'store/product_details.html')

    def test_store_search_toolbar(self):
        """Test Store's search toolbar returns results to store template"""

        product_page = self.client.get('/store/', {'q': self.product.name})
        self.assertEqual(product_page.status_code, 200)
        self.assertTemplateUsed(product_page, 'store/store.html')

    def test_store_browse_category(self):
        """Test Store's category browsing returns results to store templates"""

        category = Category.objects.create(name='category test name')

        category_page = self.client.get('/store/', {'category': category.name})
        self.assertEqual(category_page.status_code, 200)
        self.assertTemplateUsed(category_page, 'store/store.html')
Пример #5
0
def mail(request):
    if request.method == "POST":
        name = (request.POST["name"])
        price = request.POST["price"]
        incoming_prod = Product.objects.filter(name="name")

        if incoming_prod.exists():
            print('email exists')
        else:
            new_product = Product(name=name, price=price)
            new_product.save()

    context = {"webaddress": webaddress[0]}
    return HttpResponse({"webaddress": webaddress[0]})
Пример #6
0
    def run(self, file, datafeed_id):
        import ipdb
        ipdb.set_trace()

        df = pd.read_csv(file, sep=';', names=['id', 'category',
                                               'gender']).drop_duplicates()

        for g, c in product(chain(range(1, 5), [20]),
                            chain(range(5, 20), [21, 22])):
            gc = df[(df['gender'] == g) & (df['category'] == c)]
            Product.update({
                Product.category: c,
                Product.gender: g
            }).where(Product.id << list(gc.id)).execute()
            print('updated: {}, {}: {}'.format(c, g, len(gc)))
Пример #7
0
    def setUp(self):
        # Create a product with its image file
        self.product_data = {
            'name': 'test product name',
            'description': 'test product description',
            'base_price': 49.99,
        }
        with open(f'{settings.BASE_DIR}/store/tests/_test_file_1.png',
                  'rb') as image_file:
            image = ImageFile(image_file)

            self.product = Product(**self.product_data)
            self.product.image.save(new_image_path(self.product, image.name),
                                    image)
            self.product.save()
Пример #8
0
    def handle(self, *args, **options):
        Product.objects.all().delete()

        now = timezone.now()

        Product(
            pk=1,
            name='Mineral Water Strawberry',
            description=
            'Natural-flavored strawberry with an anti-oxidant kick.',
            price=1.00,
            photo='products/mineralwater-strawberry.jpg',
        ).save()
        Product(
            pk=2,
            name='Mineral Water Raspberry',
            description='Flavoured with raspberry, loaded with anti-oxidants.',
            price=2.00,
            photo='products/mineralwater-raspberry.jpg',
            sale_start=now + timedelta(days=20),
            sale_end=None,
        ).save()
        Product(
            pk=3,
            name='Vitamin A 10,000 IU (125 caplets)',
            price=3.00,
            description=
            'Vitamin A is essential for normal and night vision, and helps maintain healthy skin and mucous membranes.',
            sale_start=now - timedelta(days=10),
            sale_end=None,
            photo='products/vitamin-a.jpg',
        ).save()
        Product(
            pk=4,
            name='Vitamin B-Complex (100 caplets)',
            price=3.00,
            description=
            'Contains a combination of essential B vitamins that help convert food to energy.',
            sale_start=now,
            sale_end=now + timedelta(days=10),
            photo='products/vitamin-bcomplex.jpg',
        ).save()

        Order.objects.all().delete()

        for i in range(1, 11):
            Order(pk=i, product_id=i % 4 + 1,
                  quantity=random.randint(1, 20)).save()
    def run(self, product_id, datafeed_id):
        cond = {
            'datafeed_id': datafeed_id,
        }
        if product_id:
            cond.update({'id': product_id})

        with open('recalc_shopstyle_final.txt',
                  'w') as fh, open('recalc_shopstyle_final_err.txt',
                                   'w') as eh:
            cnt = 0
            for p in Product.filter(**cond).iterator():
                raw = p.categories_raw.split('/') if p.categories_raw else []
                market = p.market_category.split(
                    '>') if p.market_category else []
                phrases = [p.name
                           ] + raw + market + [' '.join(p.params.values())]
                ctg, gnd, *_ = detect_category(phrases)
                if not all((ctg, gnd)):
                    eh.write('{}\n'.format(p.id))

                ctg = ctg or CATEGORY_UNKNOWN
                gnd = gnd or GENDER_UNDEFINED
                category_id, gender_id = CATEGORIES[ctg], CATEGORIES[gnd]

                if not (p.category == category_id and p.gender == gender_id):
                    fh.write('{};{};{}\n'.format(p.id, category_id, gender_id))

                cnt += 1
                if cnt % 10000 == 0:
                    print('Processed ', cnt)
Пример #10
0
 def get(self, request):
     cart_val = list(request.session.get('cart').keys())
     products_cart = Product.get_products_byId(cart_val)
     data = {}
     data['title'] = 'Cart'
     data['products'] = products_cart
     return render(request, 'cart.html', data)
Пример #11
0
def productlist(request, category, producer):
    data = {}
    data['category'] = ''
    data['subcategory'] = ''
    categories = Product.CATEGORIES
    for cat in categories:
        if cat[0] == category:
            data['category'] = cat[0]
        for c in cat[1]:
            if c[0] == category:
                data['subcategory'] = category
                data['subcatname'] = c[1]
                break
    startprice = request.GET.get('pr1')
    endprice = request.GET.get('pr2')
    if data['subcategory']:
        data['products'] = Product.objects.filter(category=category)
    else:
        cats = Product.get_cats_by_group(category, Product.CATEGORIES)
        data['products'] = Product.objects.filter(category__in=cats)
    if producer:
        data['products'] = data['products'].filter(producer=producer)
    if startprice:
        data['products'] = data['products'].filter(price__gt=startprice)
    if endprice:
        data['products'] = data['products'].filter(price__lt=endprice)
    data['categories'] = categories
    data['producers'] = Product.PRODUCERS
    return render(request, 'store/productlist.html', data)
Пример #12
0
def createproduct(request):
    data = {}
    if request.method != "POST":
        form = ProductForm()
        data['form'] = form
        return render(request, 'store/createproduct.html', data)
    form = ProductForm(request.POST, request.FILES)
    data['form'] = form
    if form.is_valid():
        try:
            pr = Product(**form.cleaned_data)
            pr.save()
            return redirect('createproduct')
        except Exception:
            warning(request, 'Product was not created due to some issue')
            return render(request, 'store/createproduct.html', data)
Пример #13
0
    def get(self, request):
        context = {}
        categories = Category.get_all_categories()
        category_id = request.GET.get('category')       
        if category_id:
            products = Product.get_products_by_category_id(category_id)
        else:
            products = Product.get_all_products()
        context['products'] = products
        context['categories'] = categories

        cart = request.session.get('cart')
        if not cart:
            cart = {}
        request.session['cart'] = cart
        return render(request, 'index.html', context)
Пример #14
0
def add_to_comparison(request):
    id = request.GET.get('id')  # достаем id с реквеста
    comparison = request.session.get('comparison', {})
    product = Product.get_or_none(id)

    if product is None:
        # если товара нет в бд, возвращаем такой json
        # статус 400, чтоб ajax использовал error
        return HttpResponse(json.dumps(
            {"error": f"Product with such id={id} doesn't exist"}),
                            content_type="application/json",
                            status=400)
    else:
        if product.category.name not in comparison:
            # если категории товара нет в сравнении, то создаем список с ID
            comparison[product.category.name] = [product.id]
        else:
            # если есть категория
            if product.id in comparison[product.category.name]:
                # если айди продукта уже в списке, то возвращаем такой json
                # статус 400, чтоб ajax использовал error
                return HttpResponse(json.dumps({"added": 0}),
                                    content_type="application/json",
                                    status=400)
            else:
                # если его нет в списке, то добавляем к данной категории айди товара
                comparison[product.category.name].append(product.id)
        request.session[
            'comparison'] = comparison  # переписываем в сессию список сравнения
        # дефолтный статус 200, ajax вызовет success
        return HttpResponse(json.dumps({"added": 1}),
                            content_type="application/json")
Пример #15
0
def delete_from_comparison(request, id):
    """
    Функция удаляет товар с списка сравнений
    :param request:
    :param id:
    :return:
    """
    comparison = request.session.get('comparison', {})
    product = Product.get_or_none(id)

    if product is None:
        return HttpResponse(json.dumps(
            {"error": f"Product with such id={id} doesn't exist"}),
                            content_type="application/json")
    else:
        if id in comparison[product.category.name]:
            comparison[product.category.name].remove(id)
            if not comparison[product.category.name]:
                #  если список (значение) в списке сравнений под ключем категории пустой, то мы его удаляем
                # чтоб категория не отображалась на странице списка сравнений
                del comparison[product.category.name]
            request.session[
                'comparison'] = comparison  # присваиваем списку сравнений в сессии новый список сравнений
            return redirect('comparison')
        else:
            return HttpResponse(json.dumps({"removed": 0}),
                                content_type="application/json")
Пример #16
0
def delete_from_cart(request, id):
    """
    Функция удаляет айди товара со списка ( корзины)
    :param request:
    :param id:
    :return:
    """
    cart = request.session.get('cart', [])
    product = Product.get_or_none(id)

    if product is None:
        # если такого продукта нет в БД, то возвращаем такой json
        return HttpResponse(json.dumps(
            {"error": f"Product with such id={id} doesn't exist"}),
                            content_type="application/json")
    elif id in cart:
        # если айди в корзине
        cart.remove(id)  # удялем с корзины
        request.session['cart'] = cart  # присваиваем новое значение корзине
        return redirect('cart')  # редирект на страницу с корзиной
    else:
        # если такого айди нет в корзине, то возвращаем такой json
        # по сути, если продукта нет в корзине, то он не отображается на странице
        # то-есть его можно удалить только отправив get запрос на api
        # и только в этом случае сработает этот if
        return HttpResponse(json.dumps({"removed": 0}),
                            content_type="application/json")
Пример #17
0
 def get(self, request):
     product_id = request.GET['product_id']
     product = Product.get_product_by_id(product_id)
     cart_size = Cart.get_all_products_by_user(request.user.id)
     return render(request, 'product_details.html', {
         'product': product,
         'cart_size': len(cart_size)
     })
Пример #18
0
    def get(self, request):
        cart = request.session.get('cart')
        if not cart:
            request.session['cart'] = {}
        products= None
        category = Category.get_all_category()
        categoryID = request.GET.get('category')
        if categoryID:

            products = Product.get_all_product_by_category_id(categoryID)
        else:
            products = Product.get_all_products()
        
        data = {}
        data['product']=products
        data['category']=category
        return render(request,'store/index.html',data)
Пример #19
0
 def post(self, request):
     address = request.POST.get('address')
     phone = request.POST.get('phone')
     customer = request.session.get('customer')
     cart = request.session.get('cart')
     products = Product.get_products_by_id(list(cart.keys()))
     print(address, phone, customer)
     print("Products====", products)
     print("Cart====", cart)
     return redirect('cart')
Пример #20
0
    def datafeed_process(self, params):
        datafeed = Datafeed.get(id=params.get('datafeed_id'))

        if os.path.exists(datafeed.log['download_file']):
            start_time = time.time()
            products_for_del = Product.filter(
                Product.retailer_id == datafeed.retailer_id,
                ~(Product.datafeed_id == datafeed.id), Product.active == True)
            images_for_del = Picture.filter(
                Picture.product << products_for_del)

            importer = ImportDatafeed(self._app)
            try:
                upd, ins = importer.run(datafeed.log['download_file'],
                                        datafeed.retailer.id,
                                        datafeed_id=datafeed.id)
            except Exception as e:
                datafeed.status = Datafeed.STATUS_ERROR
                datafeed.log.update(
                    {'import_error': 'Exception: {}'.format(e)})
            else:
                datafeed.status = Datafeed.STATUS_COMPLETED
                datafeed.log.update({
                    'offers_new':
                    ins,
                    'offers_updated':
                    upd,
                    'offers_deleted':
                    products_for_del.count(),
                    'images_deleted':
                    images_for_del.count(),
                    'offers_active':
                    Product.filter(retailer_id=datafeed.retailer_id,
                                   active=True).count(),
                })
        else:
            datafeed.status = Datafeed.STATUS_ERROR
            datafeed.log.update({'process_error': 'file {} does not exists'\
                                        .format(datafeed.log['download_file'])})

        datafeed.imported = datetime.datetime.now()
        datafeed.save(only=[Datafeed.status, Datafeed.log, Datafeed.imported])
        os.unlink(datafeed.log['download_file'])
    def test_product(self):
        product = Product()
        product.name = "A solution book"
        product.price = 200
        product.digital = True
        product.save()

        record = Product.objects.get(pk=1)
        self.assertEqual(record, product)
Пример #22
0
    def get(self, request):

        cart = request.session.get('cart')
        if not cart:
            request.session.cart = {}
        products = Product.get_all_products()
        categories = Category.get_all_categories()

        # Delivering filtered products by category
        categoryID = request.GET.get('category')
        if categoryID:
            products = Product.get_all_products_by_category_id(categoryID)
        else:
            products = Product.get_all_products()

        data = {'products': products, 'categories': categories}
        print("User = ", request.session.get('customer_email'))
        # return render(request, 'orders/orders.html')

        return render(request, 'index.html', data)
    def setUp(self):
        """
        Create a product with its required fields and media files before
        each tests
        """

        self.django_cat = Category.objects.create(name='django')
        self.product_data = {
            'name': 'test product name',
            'description': 'test product description',
            'base_price': 49.99,
        }
        with open(f'{settings.BASE_DIR}/store/tests/_test_file_1.png',
                  'rb') as image_file:
            image = ImageFile(image_file)

            self.product = Product(**self.product_data)
            self.product.image.save(
                new_image_path(self.product, image.name), image)
            self.product.category = self.django_cat
            self.product.save()
Пример #24
0
    def get(self, request):

        cart = request.session.get('cart')
        if not cart:
            request.session['cart'] = {}
        products = None
        categories = Category.get_all_categories()
        categoryID = request.GET.get('category')
        if categoryID:
            products = Product.get_all_products_by_CategoryId(categoryID)
        else:
            products = Product.get_all_products()
        data = {}
        data['products'] = products
        data['categories'] = categories

        # print(products)
        # return render(request,'orders/order.html')
        # return HttpResponse('<H1>Index Page</H1>')

        print("hello", request.session.get('email'))
        return render(request, 'index.html', data)
Пример #25
0
    def get(self, request):
        if request.user.is_anonymous is not True:
            print(request.user.is_seller)
            print(request.user)
            if request.user.is_seller:
                seller = Seller.objects.get(seller=request.user)
                request.session["customer"] = seller.id
            elif request.user.is_customer:
                customer = Customer.objects.get(customer=request.user)
                request.session["customer"] = customer.id

        cart = request.session.get('cart')
        categories = Category.getAllCategory()
        products = Product.getAllProduct().order_by('-id')

        if request.GET.get('id'):

            filterProductById = Product.objects.get(
                id=int(request.GET.get('id')))
            return render(request, 'productDetail.html', {
                "product": filterProductById,
                "categories": categories
            })

        if not cart:
            request.session['cart'] = {}

        if request.GET.get('category_id'):
            filterProduct = Product.getProductByFilter(
                request.GET['category_id'])
            return render(request, 'home.html', {
                "products": filterProduct,
                "categories": categories
            })

        return render(request, 'home.html', {
            "products": products,
            "categories": categories
        })
Пример #26
0
    def handle(self, *args, **options):
        ''' Method that retrieve data from API and fill tables. '''
        api = OpenFoodFactsApi()
        category = Cat_command()
        # Call command that retrieve categories from API
        category_list = category.init_category()
        for category in category_list:
            # Retrieve products of all categories in database from API
            for json_product in api.fetch_products_data_api(category):
                try:
                    product = Product.from_api(json_product)
                    product.save()
                # Do not save a product if it already exists
                except (IntegrityError, KeyError) as error:
                    logger.warn(error)
                # Link a product to all the categories it belongs to 
                # if the category exists in database
                else:
                    if 'categories' in json_product:
                        list_of_product_categories = (
                                        json_product['categories'].split(',')
                        )
                        for product_category in list_of_product_categories:
                            try:
                                category_in_db = (
                                            Category.objects.get(
                                                name=product_category.strip()
                                            )
                                )
                                product.categories.add(category_in_db)
                            except ObjectDoesNotExist:
                                last_id_inserted = Category.objects.get(
                                                            name=category
                                                    )
                                product.categories.add(last_id_inserted)

                    # Link a product to all the stores it can be found in 
                    # and save these shops in database
                    if 'stores' in json_product:
                        list_of_product_shops = (
                                        json_product['stores'].split(',')
                        )
                        for product_shop in list_of_product_shops:
                            try:
                                shop = Shop.objects.get_or_create(
                                                    name=product_shop.strip()
                                        )
                            except ValueError as error:
                                logger.warn(error)
                            else:
                                product.shops.add(shop[0])
Пример #27
0
def edit_product(request):
    if request.method == 'POST' and request.FILES['image']:
        image = request.FILES['image']

        title = request.POST['title']
        price = request.POST['price']

        description = request.POST['description']
        obj = Product()
        obj.title = title
        obj.description = description
        obj.price = price
        obj.image = image
        obj.save()
        return redirect('/custom-admin')
    return render(request, template_name='store/add_product.html')
Пример #28
0
def qchange(request, pk):
    id = request.session['logid']
    q = int(request.POST.get("quantity", ""))
    pl = Plist.objects.all().filter(tfield=pk)
    for i in pl:
        a = 0
    p = Plist()
    i.quantity = q
    j = Product()

    p = Product.objects.all()
    for j in p:
        if (j == i.product_id):
            i.price = q * j.price
            j.quantity -= q
            i.save()
            j.save()
            if (id == 64):
                return redirect('/bill')
            else:
                return redirect('/cart')

        return redirect('/cart')
Пример #29
0
def add(request, product_key):
    postdata = request.POST.copy()
    quantity = int(postdata.get('quantity', 1))
    product = Product.get(product_key)
    item = CartItem.all().filter('product = ', product).filter('cart_id = ', get_cart_id(request)).get()
    if not item:
        item = CartItem()
        item.product = product
        item.quantity = quantity
        item.cart_id = get_cart_id(request)
        item.put()
    else:
        item.quantity = item.quantity + quantity
        item.put()
    def test_orderItem(self):

        order = OrderItem()
        order.quantity = 2  #Quantity of item
        order.product = Product()
        order.product.name = "A solution book"
        order.product.price = 200  #Price of the product
        order.product.digital = True
        order.product.save()

        order.save()

        record = OrderItem.objects.get(pk=1)
        self.assertEqual(record.get_total,
                         600)  #Check if expected total equal to returned total
Пример #31
0
    def parse(self, file_input, file_output):
        re_code = re.compile(r'%2F(\w+)%2F$')
        df = pd.read_csv(file_input, sep=';', names=['url', 'original_code',
                'recommended_code', 'original_category', 'recommended_category'])
        df = df.drop(['url'], axis=1)
        df = df[df['original_category'] != df['recommended_category']]

        for prod in Product.select(Product.id, Product.url).filter(Product.retailer == 7).iterator():
            sre = re_code.search(prod.url)
            if sre:
                df = df.replace(sre.group(1), prod.id)

        df['original_id'] = pd.to_numeric(df['original_code'], errors='coerce')
        df['recommended_id'] = pd.to_numeric(df['recommended_code'], errors='coerce')
        df = df[~(df.original_id.isna() | df.recommended_id.isna())]
        df[['original_id', 'recommended_id']].to_csv(file_output, index=False)
Пример #32
0
def show_product(request, product_key, 
                 template_name="store_product.html",
                 form_class=ProductAddToCartForm):
    key = db.Key(product_key)
    query = Product.gql('WHERE __key__ = :1 AND is_active = True', key)
    product = query.get()
    if not product:
        raise Http404('Product not found!')
    page_title = product.name
    if request.method == 'POST':
        postdata = request.POST.copy()
        form = form_class(postdata)
        if form.is_valid():
            cart.add(request, product_key)
            redirect_url = urlresolvers.reverse('show_cart')
            return HttpResponseRedirect(redirect_url)
    else:
        form = form_class()
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Пример #33
0
 def test_product_empty_string_name_not_saved(self):
     product = Product(name="", price=1)
     with self.assertRaises(ValidationError):
         product.save()
         product.full_clean()
Пример #34
0
 def test_modify_quantity(self):
     product = Product(name="m", quantity=5, price=1)
     product.save()
     product.modify_quantity(2)
     prod = Product.objects.first()
     self.assertEqual(product, prod)
Пример #35
0
from store.models import Category, Product
import random
import string

pics = ['cpu_amd.jpeg', 'cpu_intel.jpeg', 'GPU.jpeg', 'gpu_amd.jpg', 'gpu_nvidia.jpeg', 'index.jpeg', 'keyboard.jpg', 'keyboard_hp.jpg', 'keyboard_razor.png']

IsInShoppingCart = [True, False]
iteration = 0

for i in range(10000):
	for j in pics:
		a = Category()
		a.name = ''.join(random.choice(string.ascii_uppercase) for _ in range(6))
		a.category_logo = random.choice(pics)
		a.save()

		for k in range(10):
			b = Product()
			b.maker = ''.join(random.choice(string.ascii_uppercase) for _ in range(6))
			b.model = ''.join(random.choice(string.digits) for _ in range(6))
			b.description = 'descr' + str(i) + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(25))
			b.price = ''.join(random.choice(string.digits) for _ in range(3))
			b.category = a
			b.product_logo = random.choice(pics)
			b.is_in_shopCart = random.choice(IsInShoppingCart)
			b.save()
			iteration += 1
			print "iteration: {}".format(iteration)
Пример #36
0
 def test_product_duplicate_name_not_saved(self):
     product = Product(name="m", price=1)
     product.save()
     product2 = Product(name="m", price=1)
     with self.assertRaises(IntegrityError):
         product2.save()
Пример #37
0
    def write_product(self, url, category):
        page = html.parse(url)
        name = unicode(page.xpath('.//div[@class="product_title"]/h1')[0].text_content())
        print 'Writing product : ' + name

        try:
            product = Product.objects.get(categories=category, name=name, store=self.store)
        except Product.DoesNotExist:
            product = Product(name=name, store=self.store)

        # try:
        #     product_info = ProductInfo.objects.get(product=product, store=self.store)
        # except ProductInfo.DoesNotExist:
        #     product_info = ProductInfo(product=product, store=self.store)

        price_els = page.xpath('.//div[@class="product-info"]//div[@class="price"]')
        if len(price_els):
            price_el = price_els[0]
        else:
            return
        old_price_els = price_el.xpath('./span[@class="price-old"]')
        if len(old_price_els):
            old_price_el = old_price_els[0]
            old_price_content = old_price_el.text_content()
            old_price = float(re.search('Rs\.([\d,\.]+)', old_price_content).group(1).replace(',', ''))
            product.original_price = old_price
            new_price_els = price_el.xpath('./span[@class="price-new"]')
            new_price_el = new_price_els[0]
            new_price_content = new_price_el.text_content()
            new_price = float(re.search('Rs\.([\d,\.]+)', new_price_content).group(1).replace(',', ''))
            product.price = new_price
        else:
            price_with_comma = re.search('Price:\s+Rs\.([\d,\.]+)', price_el.text_content()).group(1)
            product.price = float(price_with_comma.replace(',', ''))

        product.currency = self.currency
        description_text = page.xpath('.//div[@class="product-info"]//div[@class="description"]')[0].text_content()
        product.code = re.search('Product Code:\s(.+)\\n', description_text).group(1)
        availability_text = re.search('Availability:\s(.+)', description_text).group(1)

        # TODO: get vendor
        if availability_text == 'In Stock':
            product.availability = 0
        description_el = page.xpath('//div[@id="tab-description"]')[0]
        product.description = tostring(description_el)
        product.purchase_url = url
        product.save()
        product.categories.add(category)
        # TODO: write only if images are new
        # delete existing images first
        images = product.images.all()
        # product.images.clear()
        for image in images:
            image.delete()

        primary_image_url = page.xpath('//div[@class="product-info"]//div[@class="image"]/a')[0].get('href')
        image = Image(image_url=primary_image_url)
        image.save()
        product.images.add(image)
        additional_image_links = page.xpath('//div[@class="image-additional"]/a')
        for image in additional_image_links:
            image_url = image.get('href')
            image = Image(image_url=image_url)
            image.save()
            product.images.add(image)
            # product.save()