Пример #1
0
 def test_product_well_defined(self):
     product_sku = 1
     product = Product(sku_id=product_sku, description='Butter', price=1.0)
     product.save()
     product_test = Product.objects.get(sku_id=product_sku)
     assert product_test.description == product.description
     assert product_test.price == product.price
Пример #2
0
 def mutate(self, info, name):
     try:
         product = Product(name=name)
         product.save()
         return CreateProduct(success=True, product=product)
     except Exception as err:
         return CreateProduct(success=False, errors=['exception', str(err)])
Пример #3
0
    def post(self, request, *args, **kwargs):
        subCategoryId = request.data.get('subCategoryId',None)
        product_name = request.data.get('product_name',None)
        amount = request.data.get('amount',None)
        print(subCategoryId, product_name, amount)

        sub_category = ProductSubCategory.objects.get(pk=subCategoryId)
        product = Product(sub_category=sub_category,product_name=product_name, amount=amount)
        product.save()
        return Response(status=HTTP_201_CREATED)
Пример #4
0
def asin_submit(request):
#    if not UserSettings.objects.get(user=request.user).status in ABOVE_V1:
#        messages.success(request, '请购买VIP后继续使用网站功能.')
#        return redirect('/recharge')

    detail_to_user = Product_to_user.objects.filter(user=request.user,detail=True)
    asin_details = detail_to_user.values_list('asin', flat=True)
    asin_details = Product.objects.filter(id__in=asin_details)

    form = Asin_detail_Form()
    if 'asins_in' in request.POST:
        form = Asin_detail_Form(data=request.POST or None)
        print(request.POST,form.is_valid())
        if form.is_valid():
            new_asin = form.save(commit=False)
            for asin in new_asin.asins_in.splitlines():
                if not Product.objects.filter(asin=asin,country=new_asin.country,detail=True):
                    if Product.objects.filter(asin=asin,country=new_asin.country):
                        product=Product.objects.filter(asin=asin,country=new_asin.country)[0]
                        product.detail=True
                        product.save()
                    else:
                        product=Product(asin=asin,country=new_asin.country,detail=True)
                        product.save()
                    if not Product_to_user.objects.filter(asin=product,user=request.user,detail=True):
                        detail_to_user=Product_to_user(asin=product,user=request.user,detail=True)
                        detail_to_user.save()
                else:
                    product=Product.objects.get(asin=asin,country=new_asin.country,detail=True)
                    if not Product_to_user.objects.filter(asin=product,user=request.user,detail=True):
                        if Product_to_user.objects.filter(asin=product,user=request.user):
                            detail_to_user=Product_to_user.objects.get(asin=product,user=request.user)
                            detail_to_user.detail=True
                            detail_to_user.save()
                        else:
                            detail_to_user=Product_to_user(asin=product,user=request.user,detail=True)
                            detail_to_user.save()

            messages.success(request, '查询任务已经保存,稍后开始为您查询.')
            return redirect('/asin_detail/')
    elif 'delete' in request.POST:
        products=Product.objects.filter(pk__in=request.POST.getlist('delete'))
        Product_to_user.objects.filter(asin__in=products,user=request.user).prefetch_related().update(detail=False)
        return redirect('/asin_detail/')

    paginator = Paginator(asin_details, 200)
    page = request.GET.get('page')
    try:
        asin_detail_page = paginator.page(page)
    except PageNotAnInteger:
        asin_detail_page = paginator.page(1)
    except EmptyPage:
        asin_detail_page = paginator.page(paginator.num_pages)

    return render(request, 'crawler/asin_detail/asin_submit.html', {'form':form,'asin_details': asin_detail_page,})
Пример #5
0
 def render(self, context):
     recent_products = Product.get_recent_products(max_size=6)
     popular_products = Product.get_hot(max_size=6)
     template_search_list = [
         "core/shop_side_products.html",
     ]
     liststr = render_to_string(template_search_list, {
         "recent_products": recent_products,
         "popular_products": popular_products,
     }, context)
     return liststr
Пример #6
0
 def update(product_id):
     p = openfoodfacts.products.get_product(str(product_id))
     off_link = 'https://fr.openfoodfacts.org/produit/'
     updated = Product(
         id=product_id,
         name=p['product']['product_name'],
         ng=p['product']['nutrition_grades'],
         img=p['product']['selected_images']['front']['display']['fr'],
         link_off=off_link + str(product_id),
         energy=p['product']['nutriments']['energy_100g'],
         fat=p['product']['nutriments']['fat_100g'],
         saturated_fat=p['product']['nutriments']['saturated-fat_100g'],
         carbohydrate=p['product']['nutriments']['carbohydrates_100g'],
         sugars=p['product']['nutriments']['sugars_100g'],
         proteins=p['product']['nutriments']['proteins_100g'],
         salt=p['product']['nutriments']['salt_100g'])
     updated.save()
Пример #7
0
 def render(self, context):
     related_products = Product.get_hot(max_size=12)
     template_search_list = [
         "core/shop_related_products.html",
     ]
     liststr = render_to_string(template_search_list, {
         "related_products": related_products
     }, context)
     return liststr
Пример #8
0
    def test_product_name(self):
        group, _ = (Group.objects.get_or_create(description='Ferramentas'))

        product = Product()
        product.description = 'Alicate de Pressão'
        product.group = group
        product.price = 10
        product.status = Product.ACTIVE
        product.save()

        self.assertEqual(product.description, str(product))
Пример #9
0
def insert_new_product():
    """
    Endpoint to insert a new product in the database.

    :return: 200 if the request was successful, 400 or 404 in case it was not
    """
    name = request.form.get('name')
    price = request.form.get('price')
    # If either the name or the price isn't provided, return 400 Bad request (we need both!)
    if not name or not price:
        return jsonify(BAD_REQUEST_MESSAGE), 400
    else:
        try:
            new_product = Product(name=name, price=price)
            db.session.add(new_product)
            db.session.commit()
            return jsonify(new_product.as_dict()), 200
        except IntegrityError:
            return jsonify(BAD_REQUEST_MESSAGE), 400
Пример #10
0
 def get_by_article_id(cls,article_id):
     from core.models import Product
     data=dict()
     instance=cls()
     result=instance.get_item_list(article_id=article_id,require_tag_list=1)
     try:
         data['item']=result['ArticleSearch']['Articles'][0]
     except KeyError:
         data['item']={}
     data['product_content']=Product.get_by_key_name(article_id)
     return data
Пример #11
0
def add_product():
    """Only superuser can add products."""
    if not current_user.is_authenticated or not current_user.is_active:
        abort(404)  # login to use this function
    else:
        if not current_user.has_role("superuser"):
            abort(403)  # permission denied

    # get categories from database then add to choices of select field
    categories_query = db.session.query(Category).all()
    categories = [(category.category_name, category.category_name)
                  for category in categories_query]
    form = AddProductForm()
    form.categories.choices = categories
    if form.validate_on_submit():
        product_name = form.product_name.data
        sku = form.sku.data
        product_price = form.product_price.data
        product_quantity = form.product_quantity.data
        product_description = form.product_description.data
        product_image = save_product_image(form.product_image.data,
                                           form.product_name.data)
        # make a list of categories from form
        added_categories = [
            db.session.query(Category).filter_by(
                category_name=category).first()
            for category in form.categories.data
        ]
        # must have category in product when add new product
        # to Product table because it has a relastionship with
        # Category tabele
        product = Product(
            product_name=product_name,
            sku=sku,
            product_price=product_price,
            quantity=product_quantity,
            product_description=product_description,
            product_image=product_image,
            # category=category,
        )
        db.session.add(product)

        # add product to each category from form
        for category in added_categories:
            category.products.append(product)
        db.session.commit()
        flash(_(f"Add product {product.product_name} success."), "success")
        return redirect(url_for("products.add_product"))
    return render_template(
        "product/add_product.html",
        title=_("Add Product"),
        form=form,
        categories=categories_query,
    )
Пример #12
0
 def create_test_tables(self):
     """
     Creates the current model on the testing database and inserts some
     well-known sample data.
     """
     # Binds the app to the current context
     with self.app.app_context():
         # Creates the current model on the testing database
         db.create_all()
         # Adds the test entries to the database with a unique bulk operation
         objects = [
             Currency(iso_code='GBP',
                      description='Pound sterling',
                      symbol='£'),
             Product(name='Lavender heart', price=9.25, currency_iso='GBP'),
             Product(name='Personalised cufflinks',
                     price=45.,
                     currency_iso='GBP'),
             Product(name='Kids T-shirt', price=19.95, currency_iso='GBP')
         ]
         db.session.bulk_save_objects(objects)
         db.session.commit()
Пример #13
0
def home(request):
    if request.user:
        most_rated_products = Rate.get_most_rated_products(max_size=4)
        most_hot_products = Product.get_hot(max_size=4)
        recent_portfolios = Portfolio.get_latest(max_size=4)
        recent_articles = Article.get_recommended()
        activities = Activity.get_banner_activity()
        types = ProductType.objects.all()

        return render(request, "welcome.html", {"most_rated_products": most_rated_products,
                        "recent_articles": recent_articles, "types": types, 'activities': activities,  "recent_portfolios": recent_portfolios, "most_hot_products": most_hot_products})
    else:
        return render(request, "home.html")
    def handle(self, *args, **options):
        print('Deleting inventory')
        Product.objects.all().delete()
        with open(get_path('inventory.csv'), 'r') as file:
            reader = csv.DictReader(file)
            i = 0
            for row in reader:
                i += 1
                product = Product(
                    title=row['title'],
                    price=row['price'],
                    details=row['details'],
                )
                product.image.save(row['image'],
                                   File(open(get_path(row['image']), 'rb')))

                # product.save()
        print(f"{i} products loaded!")
	def handle_noargs(self, *args, **kwargs):
		print "fetching product list"
		f = urllib2.urlopen(URL)
		products = json.loads(f.read())
		
		for (i, product_data) in enumerate(products):
			try:
				product = Product.objects.get(fairtrade_org_uk_key=product_data['key'])
			except Product.DoesNotExist:
				product = Product(fairtrade_org_uk_key=product_data['key'])
			
			if product_data['manufacturer'] == 'N/A':
				manufacturer = None
			else:
				manufacturer, created = BusinessEntity.objects.get_or_create(name=product_data['manufacturer'])
			
			category = None
			# walk down category tree
			for category_name in product_data['category'].split('/'):
				if not category:
					try:
						category = ProductCategory.get_root_nodes().get(name=category_name)
					except ProductCategory.DoesNotExist:
						category = ProductCategory.add_root(name=category_name)
				else:
					try:
						category = category.get_children().get(name=category_name)
					except ProductCategory.DoesNotExist:
						category = category.add_child(name=category_name)
			
			product.name = product_data['name']
			product.manufacturer = manufacturer
			product.category = category
			if product_data['description']:
				product.description = product_data['description']
			if product_data['url']:
				product.url = product_data['url']
			product.save()
			
			if i % 100 == 0:
				print "imported %d products" % i
Пример #16
0
    def from_api_request(request: Request,
                         limit: int) -> ProductSearchResponse:
        query = request.query_params.get('query', '')

        meal_type_str = request.query_params.get('meal_type', '').lower()

        meal_type = next(
            iter([
                e for e in MealType.values if str(e).lower() == meal_type_str
            ]), MealType.Unknown)

        exclude_product_str_ids = request.query_params.get(
            'exclude_products', '').split(',')
        exclude_product_ids = list(
            filter(lambda i: i is not None,
                   [utils.try_parse_int(x) for x in exclude_product_str_ids]))
        user = request.user

        products = Product.filter_by_user_and_query(
            user, query, exclude_product_ids)[:limit]
        daily_nutrient_norms_and_totals = DailyIntakesReport.get_latest_daily_nutrient_norms_and_totals(
            user)

        if query:
            submit_str = request.query_params.get('submit', None)
            excluded_products_count = len(exclude_product_ids)

            submit = None
            if submit_str in ('0', 'false'):
                submit = False
            elif submit_str in ('1', 'true'):
                submit = True

            ProductSearchLog.insert_from_product_search(
                query, products, user, submit, excluded_products_count,
                meal_type)

        return ProductSearchResponse(
            products=products,
            query=query,
            daily_nutrient_norms_and_totals=daily_nutrient_norms_and_totals,
        )
Пример #17
0
    def test_create_new_product_successful(self):
        """Test create new product is succesful"""
        prodType = 'T-Shirt'
        product_name = 'Levis'
        field1 = 'White'
        field2 = 'Small'
        field3 = 'Vneck'
        stock = 0
        product_obj = Product(prodType=prodType,
                              product_name=product_name,
                              field1=field1,
                              field2=field2,
                              field3=field3,
                              stock=stock)

        self.assertEqual(product_obj.prodType, prodType)
        self.assertEqual(product_obj.product_name, product_name)
        self.assertEqual(product_obj.field1, field1)
        self.assertEqual(product_obj.field2, field2)
        self.assertEqual(product_obj.field3, field3)
        self.assertEqual(product_obj.stock, stock)
Пример #18
0
    def test_command_delete(self, mock_get_products):
        """
        Test for the command : python manage.py database --delete
        """

        mock_get_products.return_value = Mock()
        mock_get_products.return_value.json.return_value = mock_api_return

        # Register a category for the test.
        cat = Category(name='test_category')
        cat.save()

        # Register a product for the test.
        Product(name='prod_name',
                code='1',
                nutrition_grade='a',
                image_nutrition_url='image_nutrition_url',
                image_small_product_url='image_small_product_url',
                image_full_product_url='image_full_product_url',
                url='url',
                category=cat).save()

        category_count_before_del = Category.objects.all().count()
        product_count_before_del = Product.objects.all().count()

        out = StringIO()
        call_command('database', '--delete', stdout=out)

        category_count_after_del = Category.objects.all().count()
        product_count_after_del = Product.objects.all().count()

        # Before delete
        self.assertEqual(category_count_before_del, 1)
        self.assertEqual(product_count_before_del, 1)

        # After delete
        self.assertEqual(category_count_after_del, 0)
        self.assertEqual(product_count_after_del, 0)

        self.assertIn('1 products and 1 categories deleted', out.getvalue())
Пример #19
0
def parse_shop(link_type, driver):
    items = []
    old_products = list(
        Product.objects.filter(link__link_type=link_type).values_list(
            "pk", flat=True))
    parse_func = map_shop_name_to_func_parse[link_type]
    links = Link.objects.filter(link_type=link_type).values_list(
        "url", "shop_name", "id")
    logger.info("Start parse {}. Links: {}".format(link_type, len(links)))
    sum_len = 0
    for url, shop_name, link_id in links:
        try:
            for item in parse_func(driver, url):
                if item.get('url_original'):
                    item.update(shop_name=shop_name, link_id=link_id)
                    items.append(Product(**item))
            Product.objects.bulk_create(items)
            sum_len += len(items)
            items.clear()
        except Exception:
            print(traceback.format_exc())
            logger.warning("Item is skipped")
    logger.info("Number {} items: {}".format(link_type, sum_len))
    Product.objects.filter(pk__in=old_products).delete()
Пример #20
0
def search():
    if not g.search_form.validate_on_submit():
        return redirect(url_for(""))
    page = request.args.get("page", 1, type=int)
    posts, total = Product.search(
        g.search_form.q.data, page, current_app.config["PRODUCT_PER_PAGE"]
    )
    next_url = (
        url_for("main.search", q=g.search_form.q.data, page=page + 1)
        if total > page * current_app.config["POST_PER_PAGE"]
        else None
    )
    previous_url = (
        url_for("main.search", q=q.search_form.data, page=page - 1)
        if page > 1
        else None
    )
    return render_template(
        "search.html",
        title=_("Search"),
        posts=posts,
        next_url=next_url,
        previous_url=previous_url,
    )
Пример #21
0
    def form_valid(self, request, form, files):
        """ Enters here iff form is valid in the post() method """
        print(request.user)
        tags = form.cleaned_data[
            'tags']  # Returns a string representation of a  dictionaries: [{"value":"i'm_a_tag"},{"value":"tag_me"}]
        tags = json.loads(tags)  # Use json to convert it into a dic
        product = Product(
            owner=request.user,
            title=form.cleaned_data['product_title'],
            desc=form.cleaned_data['product_description'],
        )
        product.save()

        # Add tag list to taggit
        [product.tags.add(tag['value']) for tag in tags]
        product.save()

        for image in files:
            ProductImages(product=product, image=image).save()

        return super(PostProduct, self).form_valid(form)
Пример #22
0
 def test_do_not_allow_null_description(self):
     try:
         Product(sku_id=2, description=None, price=1.0).save()
     except IntegrityError:
         pass
Пример #23
0
def product_submit(request):
    #if not UserSettings.objects.get(user=request.user).status in ABOVE_V1:
    #    messages.success(request, '请购买VIP后继续使用网站功能.')
    #    return redirect('/recharge')

    form = Product_Form(data=request.POST or None)
    if form.is_valid():
        new_asin = form.save(commit=False)
        overflow = False
        for asin in new_asin.asins_in.splitlines():
            if len(
                    Product_to_user.objects.filter(user=request.user,
                                                   review_qa=True)) > 4:
                overflow = True
            else:
                if not Product.objects.filter(
                        asin=asin, country=new_asin.country, review_qa=True):
                    if Product.objects.filter(asin=asin,
                                              country=new_asin.country):
                        product = Product.objects.filter(
                            asin=asin, country=new_asin.country)[0]
                        product.review_qa = True
                        product.review_qa_apply_time = timezone.now()
                        product.save()
                    else:
                        product = Product(asin=asin,
                                          country=new_asin.country,
                                          review_qa_apply_time=timezone.now(),
                                          review_qa=True)
                        product.save()
                    if not Product_to_user.objects.filter(
                            asin=product, user=request.user, review_qa=True):
                        detail_to_user = Product_to_user(asin=product,
                                                         user=request.user,
                                                         review_qa=True)
                        detail_to_user.save()
                else:
                    product = Product.objects.get(asin=asin,
                                                  country=new_asin.country,
                                                  review_qa=True)
                    if not Product_to_user.objects.filter(
                            asin=product, user=request.user, review_qa=True):
                        if Product_to_user.objects.filter(asin=product,
                                                          user=request.user):
                            detail_to_user = Product_to_user.objects.get(
                                asin=product, user=request.user)
                            detail_to_user.review_qa = True
                            detail_to_user.save()
                        else:
                            detail_to_user = Product_to_user(asin=product,
                                                             user=request.user,
                                                             review_qa=True)
                            detail_to_user.save()
        if overflow:
            messages.success(request, '抓取评论和问答的服务处于试用期,每个用户最多采集五个ASIN.')
        else:
            messages.success(request, '查询任务已经保存,稍后开始为您查询.')
        return redirect('/review_qa_collect')

    product_to_user = Product_to_user.objects.filter(user=request.user,
                                                     review_qa=True)
    products = product_to_user.values_list('asin', flat=True)
    products = Product.objects.filter(id__in=products)

    paginator = Paginator(products, 12)
    page = request.GET.get('page')
    try:
        products_page = paginator.page(page)
    except PageNotAnInteger:
        products_page = paginator.page(1)
    except EmptyPage:
        products_page = paginator.page(paginator.num_pages)
    return render(request, 'crawler/review_qa_collect/product_submit.html', {
        'form': form,
        'products': products_page,
        'page': page
    })
Пример #24
0
    def test_unique_slug(self):
        product_a = Product()
        product_a.name = "a"
        product_a.save()

        product_b = Product()
        product_b.name = product_a.name
        product_b.site = Site.objects.get(pk=2)
        product_b.save()

        product_c = Product()
        product_c.name = product_a.name
        product_c.save()

        self.assertNotEqual(product_a.slug, product_c.slug)
        self.assertEqual(product_a.slug, product_b.slug)
Пример #25
0
    def test_unique_sku(self):
        product_a = Product()
        product_a.name = 'a'
        product_a.sku = 'a'
        product_a.save()

        product_b = Product()
        product_b.name = 'a'
        product_b.sku = 'a'
        with self.assertRaises(IntegrityError):
            with transaction.atomic():
                product_b.save()
Пример #26
0
 def setUp(self):
     self.new_product = Product()
Пример #27
0
class ModelProductTests(TestCase):

    fixtures = ['user', 'unit_test']

    def setUp(self):
        self.new_product = Product()

    def test_create_product(self):
        self.new_product.sku = generate_sku()
        self.new_product.name = "Chocolate Chips"
        self.new_product.available = True

        self.new_product.save()

        self.assertTrue(self.new_product.pk)
        
    def test_unique_sku(self):
        product_a = Product()
        product_a.name = 'a'
        product_a.sku = 'a'
        product_a.save()

        product_b = Product()
        product_b.name = 'a'
        product_b.sku = 'a'
        with self.assertRaises(IntegrityError):
            with transaction.atomic():
                product_b.save()

    def test_unique_slug(self):
        product_a = Product()
        product_a.name = "a"
        product_a.save()

        product_b = Product()
        product_b.name = product_a.name
        product_b.site = Site.objects.get(pk=2)
        product_b.save()

        product_c = Product()
        product_c.name = product_a.name
        product_c.save()

        self.assertNotEqual(product_a.slug, product_c.slug)
        self.assertEqual(product_a.slug, product_b.slug)

    def test_valid_msrp(self):
        msrp =  "JPY,10.99"
        
        self.assertIsNone(validate_msrp_format(msrp))
        
    
    def test_raise_error_invalid_country_code_msrp(self):
        msrp = "JP,10.00"
        with self.assertRaises(ValidationError):
            validate_msrp_format(msrp)

    def test_raise_error_no_price_on_msrp(self):
        msrp = "MXN,"
        with self.assertRaises(ValidationError):
            validate_msrp_format(msrp)

    def test_raise_error_no_country_on_msrp(self):
        msrp = ",10.00"
        with self.assertRaises(ValidationError):
            validate_msrp_format(msrp)
    
    def test_raise_error_only_comma_msrp(self):
        msrp = ","
        with self.assertRaises(ValidationError):
            validate_msrp_format(msrp)
    
    def test_get_best_currency_success(self):
        product = Product.objects.get(pk=1)
        
        self.assertEquals(product.get_best_currency(), 'usd')

    def test_get_best_currency_fail(self):
        product = Product.objects.get(pk=1)
        
        self.assertEquals(product.get_best_currency('mxn'), 'usd')

    def test_create_product_valid_msrp(self):
        self.assertIsNone(validate_msrp({'msrp': {'default': 'usd', 'usd': 20 }}))

    def test_create_product_valid_msrp_multiple_currencies(self):
        self.assertIsNone(validate_msrp({'msrp': {'default': 'usd', 'usd': 20, 'jpy': 12 }}))

    def test_create_product_in_valid_msrp(self):
        with self.assertRaises(ValidationError):
            validate_msrp({'msrp': {'default': 'rub', 'rub': 20 }})

    def test_create_product_in_valid_msrp(self):
        with self.assertRaises(ValidationError):
            validate_msrp({'msrp': {'default': 'usd', 'usd': 21, 'rub': 20 }})
Пример #28
0
        else:
            outofline = 0
    else:
        outofline = 0
    ncm = gen_ncm()
    b = random.randint(1, 20)
    brand = Brand.objects.get(pk=b)
    product = product_list[i]['product']
    price = float(gen_decimal(4, 2))
    ipi = 0
    if imported == 1:
        ipi = float(gen_ipi())
        if ipi > 0.5:
            ipi = ipi - 0.5
    stock = random.randint(1, 999)
    stock_min = random.randint(1, 20)
    obj = Product(
        imported=imported,
        outofline=outofline,
        ncm=ncm,
        brand=brand,
        product=product,
        price=price,
        ipi=ipi,
        stock=stock,
        stock_min=stock_min,
    )
    obj.save()

print('%d Produtos salvo com sucesso.' % REPEAT)
Пример #29
0
 def test_product(self):
     cards = Product(name="Cards")
     cards.save()
     product = Product.objects.get(name__iexact="Cards")
     self.assertEqual(product.__unicode__(), 'Cards')
Пример #30
0
    def populate_db(self):
        """
        This method populates the database with Open Food Facts data when the Product and Category tables are empty.
        If these tables are not empty, the user will be notified.
        The Open Food Facts API is used.
        """

        if self.db_is_empty():
            try:
                self.stdout.write(
                    "Saving Open Food Facts data in the local database ...")
                self.stdout.write("Please wait ...")

                # Get API configuration
                api_url = API_CONFIG["url"]
                api_criteria = API_CONFIG["criteria"]
                nutrition_grades = API_CONFIG["nutrition_grades"]
                openfoodfacts_categories = OFF_CATS["categories"]

                for category in openfoodfacts_categories:
                    api_criteria.update({"tag_0": category})

                    # Save the category in the database
                    cat = Category(name=category)
                    cat.save()

                    for nutrition_grade in nutrition_grades:
                        api_criteria.update({"tag_1": nutrition_grade})
                        # Call API
                        response = requests.get(api_url, params=api_criteria)
                        data = response.json()
                        products = data['products']

                        # Save the product in the database
                        for product in products:
                            if product.get('image_nutrition_url') and product.get('image_small_url') \
                                    and product.get('code') != "1":
                                Product(name=product.get(
                                    'product_name').lower().capitalize(),
                                        code=product.get('code'),
                                        nutrition_grade=product.get(
                                            'nutrition_grades'),
                                        image_nutrition_url=product.get(
                                            'image_nutrition_url'),
                                        image_small_product_url=product.get(
                                            'image_small_url'),
                                        image_full_product_url=product.get(
                                            'image_small_url').replace(
                                                '200.jpg', 'full.jpg'),
                                        url=product.get('url'),
                                        category=cat).save()

                self.stdout.write(
                    "-> Database populated with Open Food Facts data.")
                self.stdout.write(
                    f"-> {self.product_count} products and {self.category_count} "
                    f"categories were registered.")

            except requests.exceptions.ConnectionError as err:
                # If there is an API connection problem, the Category table is flushed.
                Category.objects.all().delete()
                print(f'Error : {err}')
        else:
            self.stdout.write("Database is not empty !")
            self.stdout.write(
                "Please use --delete before repopulating the database.")
Пример #31
0
def save(request):
    """
    AJAX function, used to save (or update) product in database
    If user is connected & the product is not already in DB
        Add product & bind it to the user
    If user is connected, the product is in DB but not bounded to the user
        Update the product with the (maybe) new value
        Add the user to the product
    If user not connected
        Do nothing & ask him to login
    """
    # p = product(s).
    # Convert request.GET string to list with ast.literal_eval()
    sub = ast.literal_eval(request.GET.get('substitute'))
    if request.user.is_authenticated:
        current_user = request.user.id
        if Product.objects.filter(id=sub['id'], users=current_user).exists():
            data = {
                'success':
                False,
                'message':
                'Le produit "' + sub['name'] +
                '" est déjà associé à votre compte'
            }
        else:
            """
            'p' will erase previously stored value for a given (id) product
            It will conserve ManyToMany relation
            The user requesting the save will be added alongside with past one
            It act as an update for the DataBase
            """
            p = Product(
                id=sub['id'],
                name=sub['name'],
                ng=sub['ng'],
                img=sub['img'],
                link_off=sub['link_off'],
                energy=sub['energy'],
                fat=sub['fat'],
                saturated_fat=sub['saturated_fat'],
                carbohydrate=sub['carbohydrate'],
                sugars=sub['sugars'],
                proteins=sub['proteins'],
                salt=sub['salt'],
            )
            p.save()
            p.users.add(current_user)
            data = {
                'success':
                True,
                'message':
                'Le produit "' + sub['name'] +
                '" a bien été ajouté à votre compte'
            }
            logger.info('New save',
                        exc_info=True,
                        extra={
                            'product_id': p.id,
                            'product_name': p.name
                        })
    else:
        data = {
            'success': False,
            'message': "Veuillez vous connecter avant d'enregistrer un produit"
        }
    return JsonResponse(data)