예제 #1
0
 def testIngredientSwapProductAndRecipe(self):
     author = User(username='******', password='******')
     author.save()
     cat = Category(name='test')
     cat.save()
     r = Recipe(category=cat, name_addition='recipe', author=author)
     r.save()
     a = Product(category=cat,
                 name_addition='a',
                 author=author,
                 reference_amount=100.0,
                 calories=100.0)
     a.save()
     i = Ingredient(recipe=r, amount=10.0)
     i.food = a
     i.save()
     self.assertEqual(i.product, a)
     self.assertIsNone(i.food_is_recipe)
     r2 = Recipe(category=cat, name_addition='recipe2', author=author)
     r2.save()
     i2 = Ingredient(recipe=r, amount=10.0)
     i2.food = a
     i2.save()
     i.food = r2
     i.save()
     self.assertIsNone(i.product)
     self.assertEqual(i.food_is_recipe, r2)
     i.food = a
     i.save()
     self.assertEqual(i.product, a)
     self.assertIsNone(i.food_is_recipe)
예제 #2
0
    def testServingFood(self):
        def set_food(x, food):
            x.food = food

        author = User(username='******', password='******')
        author.save()
        cat = Category(name='test')
        cat.save()
        s = Serving(name="Testspoon", size=25)
        self.assertRaises(NoFoodException, set_food, s, cat)
        a = Product(category=cat,
                    name_addition='a',
                    author=author,
                    reference_amount=100.0,
                    calories=100.0)
        a.save()
        s.food = a
        s.save()
        self.assertEqual(str(s.food), "test: a")
        self.assertIsNone(s.food_is_recipe)
        r = Recipe(category=cat, name_addition='recipe', author=author)
        r.save()
        i1 = Ingredient(recipe=r, amount=100.0)
        i1.food = a
        i1.save()
        s.food = r
        self.assertEqual(str(s.food), "test: recipe")
        self.assertIsNone(s.product)
        s.food = a
        s.save()
        self.assertEqual(str(s.food), "test: a")
        self.assertIsNone(s.food_is_recipe)
예제 #3
0
    def delete(
        self,
        request: Request,
    ) -> Response:
        """
        Delete product by its id.
        :param request: request with "id" field (must be string).
        :return: response whether request is successful.
        """

        profile: Profile = get_profile_by_token(request)

        if not profile.has_valid_token or profile.role != Admin:
            return INVALID_CREDENTIALS

        id_: str = request.query_params.get("id")
        try:
            Product.delete_by_id(id_)
        except (TypeError, ValueError, Product.DoesNotExist):
            return PRODUCT_NOT_FOUND

        return Response(
            data={
                "message": "Product was deleted successfully.",
            },
            status=HTTP_200_OK,
        )
예제 #4
0
def populate_db():
    """Populate db with sample data"""
    data = [
        Product(
            id=1, name="Ciabatta", price="10", description="Italian Bread"
        ),
        Product(id=2, name="Baguete", price="15", description="French Bread"),
        Product(id=3, name="Pretzel", price="20", description="German Bread"),
    ]
    db.session.bulk_save_objects(data)
    db.session.commit()
    return Product.query.all()
예제 #5
0
def upload(current_user):
    image_file = request.json.get('image_file', None)
    name = request.json.get('name', None)
    company = request.json.get('company', None)
    price = request.json.get('price', None)
    description = request.json.get('description', None)
    if image_file!="" and name!="" and company!="" and price!="" and description!="":
        product = Product(image_file=image_file, name=name, company=company,price=price, description=description)
        product.uploaded_by = current_user
        db.session.add(product)
        db.session.commit()
        return jsonify({'uploaded': True})
    else:
        return jsonify({'uploaded': False})
예제 #6
0
 def testRecipeAdjustReferenceAmount(self):
     author = User(username='******', password='******')
     author.save()
     cat = Category(name='test')
     cat.save()
     r = Recipe(category=cat, name_addition='recipe', author=author)
     r.save()
     a = Product(category=cat,
                 name_addition='a',
                 author=author,
                 reference_amount=100.0,
                 calories=100.0)
     a.save()
     b = Product(category=cat,
                 name_addition='b',
                 author=author,
                 reference_amount=100.0,
                 calories=20.0)
     b.save()
     i1 = Ingredient(recipe=r, amount=100.0)
     i1.food = a
     i1.save()
     i2 = Ingredient(recipe=r, amount=200.0)
     i2.food = b
     i2.save()
     self.assertAlmostEqual(r.reference_amount, 300, 5)
     r.reference_amount = 100
     self.assertAlmostEqual(r.ingredients.all()[0].amount, 100 / 3, 5)
     self.assertAlmostEqual(r.ingredients.all()[1].amount, 200 / 3, 5)
     self.assertAlmostEqual(r.reference_amount, 100, 5)
예제 #7
0
def product_add_handle(request):
	if not request.user.is_authenticated():
		return redirect('/backend/login/')
	if request.method == "POST":
		p_id  = request.POST.get('p_id','')
		s_id  = request.POST.get('s_id','')
		t_id  = request.POST.get('t_id','0')
		name  = request.POST.get('name','')
		photo = request.FILES.get('photo',None)
		price = request.POST.get('price','')
		key_words = request.POST.get('key_words', '')
		is_hot = request.POST.get('is_hot','')
		is_new = request.POST.get('is_new','')
		brands = request.POST.get('brands','')
		color  = request.POST.getlist('color','')
		size   = request.POST.getlist('size','')
		content = request.POST.get('content','')
		if not is_hot:
			is_hot = False
		if not is_new:
			is_new = False
		is_size = ''
		#是否选择尺寸  有		
		if size:
			for i in size:
				is_size += i + ','    #以 ',' 分割,组合成字符串
		is_color = ''
		#是否选择颜色  有		
		if color:
			for i in color:
				is_color += i + ','    #以 ',' 分割,组合成字符串
		p = Product(
			p_id = p_id,
			s_id = s_id,
			t_id = t_id,
			name = name,
			photo = photo,
			price = price,
			key_words = key_words,
			is_hot = is_hot,
			is_new = is_new,
			brands = brands,
			color  = is_color,
			size   = is_size,
			content = content,
			)
		p.save()
		return HttpResponseRedirect('/backend/product_add/')
	return HttpResponse('请求方法错误...')
예제 #8
0
 def testIngredientSetProperties(self):
     author = User(username='******', password='******')
     author.save()
     cat = Category(name='test')
     cat.save()
     r = Recipe(category=cat, name_addition='recipe', author=author)
     r.save()
     a = Product(category=cat,
                 name_addition='a',
                 author=author,
                 reference_amount=100.0,
                 calories=100.0)
     a.save()
     i = Ingredient(recipe=r, amount=10.0)
     i.food = a
     i.save()
     i.calories = 20
     self.assertAlmostEqual(i.amount, 20, 5)
     i.total_fat = 1
     i.saturated_fat = 1
     i.cholesterol = 1
     i.protein = 1
     i.total_carbs = 1
     i.sugar = 1
     i.dietary_fiber = 1
     i.salt = 1
     i.sodium = 1
     i.potassium = 1
     i.copper = 1
     i.iron = 1
     i.magnesium = 1
     i.manganese = 1
     i.zinc = 1
     i.phosphorous = 1
     i.sulphur = 1
     i.chloro = 1
     i.fluoric = 1
     i.vitamin_b1 = 1
     i.vitamin_b12 = 1
     i.vitamin_b6 = 1
     i.vitamin_c = 1
     i.vitamin_d = 1
     i.vitamin_e = 1
     for prop in [
             'total_fat', 'saturated_fat', 'cholesterol', 'protein',
             'total_carbs', 'sugar', 'dietary_fiber', 'salt', 'sodium',
             'potassium', 'copper', 'iron', 'magnesium', 'manganese',
             'zinc', 'phosphorous', 'sulphur', 'chloro', 'fluoric',
             'vitamin_b1', 'vitamin_b12', 'vitamin_b6', 'vitamin_c',
             'vitamin_d', 'vitamin_e'
     ]:
         i.amount = 20
         i.__setattr__(prop, 10)
         self.assertAlmostEqual(i.amount, 20, 5)
         a.__setattr__(prop, 5)
         a.save()
         i.__setattr__(prop, 10)
         self.assertAlmostEqual(i.amount, 200, 5)
예제 #9
0
    def get(
        self,
        request: Request,
    ) -> Response:
        """
        Get info about product by its id.
        :param request: request with "id" field.
        :return: response whether request is successful with info about product.
        """

        profile: Profile = get_profile_by_token(request)

        if not profile.has_valid_token:
            return INVALID_CREDENTIALS

        id_: str = request.query_params.get("id")
        try:
            product: Product = Product.get_by_id(id_)
        except (ValueError, TypeError, Product.DoesNotExist):
            return PRODUCT_NOT_FOUND

        serializer = ProductSerializer(
            product,
            many=False,
        )

        return Response(
            data=serializer.data,
            status=HTTP_200_OK,
        )
예제 #10
0
 def testPrintIngredtient(self):
     author = User(username='******', password='******')
     author.save()
     cat = Category(name='test')
     cat.save()
     r = Recipe(category=cat, name_addition='recipe', author=author)
     r.save()
     a = Product(category=cat,
                 name_addition='a',
                 author=author,
                 reference_amount=100.0,
                 calories=100.0)
     a.protein = 30.0
     a.save()
     i = Ingredient(recipe=r, amount=10.0)
     i.food = a
     self.assertEqual(str(i), "10.0g of test: a")
예제 #11
0
    def create(self, request):
        file = request.FILES['csv']

        destination = open('batch.csv', 'wb')
        for chunk in file.chunks():
            destination.write(chunk)
        destination.close()
        products = []

        with open('batch.csv', "r") as file:
            csv_reader = csv.reader(file, delimiter=',')

            for line in csv_reader:
                category = Category.objects.get_or_create(name=line[2])
                types = [
                    Type.objects.get_or_create(name=name)
                    for name in line[3].split("|")
                ]

                try:

                    product = Product(name=line[0],
                                      description=line[1],
                                      category=category[0],
                                      price=line[4],
                                      brand=line[5],
                                      quantity=line[6])

                    product.save()
                    for type in types:
                        product.type.add(type[0])
                    products.append(product)
                except:
                    if category[1]:
                        category[0].delete()
                    for type in types:
                        if type[1]:
                            type[0].delete()
                    continue

        os.remove('batch.csv')
        serializer = ProductSerializer(products,
                                       context={'request': request},
                                       many=True)
        return Response(serializer.data)
예제 #12
0
    def create(self, request):
        category = Category.objects.get_or_create(
            name=request.data['category'])
        subcategory = Subcategory.objects.get_or_create(
            name=request.data['subcategory'])
        instance = Product(name=request.data['name'],
                           description=request.data['description'],
                           category=category[0],
                           subcategory=subcategory[0],
                           price=request.data['price'],
                           brand=request.data['brand'],
                           quantity=request.data['quantity'],
                           picture=request.data['picture'],
                           documentation=request.data['documentation'])
        instance.save()
        for type_name in request.data['type'].split(","):
            type = Type.objects.get_or_create(name=type_name)
            instance.type.add(type[0])
        serializer = ProductSerializer(instance, many=False)

        return Response(serializer.data)
예제 #13
0
    def post(
        self,
        request: Request,
    ) -> Response:
        """
        Edit product info.
        :param request: request with "id" and optional "title" and "category" fields.
        :return: response whether request is successful.
        """

        profile: Profile = get_profile_by_token(request)

        if not profile.has_valid_token or profile.role != Admin:
            return INVALID_CREDENTIALS

        id_: str = request.data.get("id")
        try:
            product: Product = Product.get_by_id(id_)
        except (ValueError, TypeError, Product.DoesNotExist):
            return PRODUCT_NOT_FOUND

        title: str = request.data.get("title")
        if title:
            product.title = title

        category: str = request.data.get("category")
        if category is not None:
            product.category = category

        product.save()

        return Response(
            data={
                "message": "Product info was edited successfully.",
            },
            status=HTTP_200_OK,
        )
예제 #14
0
    def put(
        self,
        request: Request,
    ) -> Response:
        """
        Create new product.
        :param request: request with "title" and optional "category" string fields.
        :return: response whether request is successful.
        """

        profile: Profile = get_profile_by_token(request)

        if not profile.has_valid_token or profile.role != Admin:
            return INVALID_CREDENTIALS

        title: str = request.data.get("title")
        if not title:
            return Response(
                data={
                    "message": "Title must not be empty.",
                },
                status=HTTP_400_BAD_REQUEST,
            )

        category: str = request.data.get("category")

        id_ = Product.create(
            title=title,
            category=category,
        )

        return Response(
            data={
                "id": id_,
            },
            status=HTTP_200_OK,
        )
예제 #15
0
 def handle(self, *args, **options):
     try:
         pina = User.objects.get(username='******')
     except User.DoesNotExist:
         pina = User(username='******',
                     first_name='Pina',
                     last_name='Merkert',
                     email='*****@*****.**')
         pina.set_password('1234Geheim')
         pina.save()
     paths = [
         os.path.join('jsonAPI', 'fixtures', filename)
         for filename in os.listdir(os.path.join('jsonAPI', 'fixtures'))
     ]
     paths = sorted(paths)
     for file in paths:
         print("Loading data from {}.".format(file))
         with open(file, 'r', encoding='utf-8') as f:
             cat_table = []
             product_table = []
             recipe_table = []
             for data in json.loads(f.read()):
                 if 'model' in data and data['model'] == 'backend.Category' and \
                         'fields' in data and 'name' in data['fields']:
                     try:
                         category = Category.objects.get(
                             name=data['fields']['name'])
                     except Category.DoesNotExist:
                         category = Category(name=data['fields']['name'])
                         category.save()
                     if 'pk' in data:
                         cat_table.append({
                             'fixture_pk': data['pk'],
                             'real_category': category
                         })
                 if 'model' in data and data['model'] == 'backend.Product' and 'fields' in data and \
                         'reference_amount' in data['fields'] and 'calories' in data['fields']:
                     fields = data['fields']
                     category, name_addition = self.get_category_and_name_addition(
                         fields, cat_table)
                     if type(category) is not Category or type(
                             name_addition) is not str:
                         continue
                     try:
                         reference_amount = float(
                             fields['reference_amount'])
                         calories = float(fields['calories'])
                     except ValueError:
                         continue
                     product_query = Product.objects.filter(
                         category=category,
                         name_addition=name_addition,
                         reference_amount=reference_amount,
                         calories=calories)
                     save_new_product = False
                     if product_query.count() >= 1:
                         product = product_query[0]
                     else:
                         save_new_product = True
                         product = Product(
                             category=category,
                             name_addition=name_addition,
                             author=pina,
                             reference_amount=reference_amount,
                             calories=calories)
                     field_cache = {}
                     if 'creation_date' in fields:
                         try:
                             creation_date = datetime.strptime(
                                 fields['creation_date'],
                                 '%Y-%m-%d %H:%M:%S.%f%z')
                             if product.creation_date is None or product.creation_date != creation_date:
                                 product.creation_date = creation_date
                                 save_new_product = True
                             field_cache['creation_date'] = creation_date
                         except ValueError:
                             pass
                     for k in [
                             "total_fat", "saturated_fat", "cholesterol",
                             "protein", "total_carbs", "sugar",
                             "dietary_fiber", "salt", "sodium", "potassium",
                             "copper", "iron", "magnesium", "manganese",
                             "zinc", "phosphorous", "sulphur", "chloro",
                             "fluoric", "vitamin_b1", "vitamin_b12",
                             "vitamin_b6", "vitamin_c", "vitamin_d",
                             "vitamin_e"
                     ]:
                         if k in fields:
                             try:
                                 field_value = float(fields[k])
                             except ValueError:
                                 continue
                             if product.__getattribute__(k) is None:
                                 product.__setattr__(k, field_value)
                                 save_new_product = True
                             if product.__getattribute__(k) != field_value:
                                 product = Product(
                                     category=category,
                                     name_addition=name_addition,
                                     author=pina,
                                     reference_amount=reference_amount,
                                     calories=calories)
                                 product.__setattr__(k, field_value)
                                 save_new_product = True
                             field_cache[k] = field_value
                     for k in field_cache.keys():
                         product.__setattr__(k, field_cache[k])
                     if save_new_product:
                         product.save()
                         print("Adding Product: " + str(product))
                     else:
                         print("Product " + str(product) +
                               " is already up to date.")
                     if 'pk' in data:
                         product_table.append({
                             'fixture_pk': data['pk'],
                             'real_product': product
                         })
                 if 'model' in data and data[
                         'model'] == 'backend.Recipe' and 'fields' in data:
                     fields = data['fields']
                     category, name_addition = self.get_category_and_name_addition(
                         fields, cat_table)
                     if type(category) is not Category or type(
                             name_addition) is not str:
                         continue
                     creation_date = None
                     if 'creation_date' in fields:
                         try:
                             creation_date = datetime.strptime(
                                 fields['creation_date'],
                                 '%Y-%m-%d %H:%M:%S.%f%z')
                         except ValueError:
                             pass
                     recipe_query = Recipe.objects.filter(
                         category=category, name_addition=name_addition)
                     if recipe_query.count() == 1:
                         recipe = recipe_query[0]
                         print("Found existing Recipe: " + str(recipe))
                     else:
                         recipe = Recipe(category=category,
                                         name_addition=name_addition,
                                         author=pina)
                         if creation_date is not None:
                             recipe.creation_date = creation_date
                         recipe.save()
                         print("Adding empty Recipe: " + str(recipe))
                     if 'pk' in data:
                         recipe_table.append({
                             'fixture_pk': data['pk'],
                             'real_recipe': recipe
                         })
                     if 'ingredients' in data:
                         for ing_data in data['ingredients']:
                             if 'name' not in ing_data or 'amount' not in ing_data:
                                 print(
                                     "This ingredient needs a 'name' and an 'amount': "
                                     + str(ing_data))
                                 continue
                             cat_str, name_add = split_name(
                                 ing_data['name'])
                             food = None
                             products = Product.objects.filter(Q(name_addition__icontains=ing_data['name']) |
                                                               Q(category__name__icontains=ing_data['name']) |
                                                               Q(category__name=cat_str,
                                                                 name_addition__icontains=name_add)).\
                                 prefetch_related('category').order_by('category__name', 'name_addition')
                             recipes = Recipe.objects.filter(Q(name_addition__icontains=ing_data['name']) |
                                                             Q(category__name__icontains=ing_data['name']) |
                                                             Q(category__name=cat_str,
                                                               name_addition__icontains=name_add)).\
                                 prefetch_related('category').order_by('category__name', 'name_addition')
                             if products.count() + recipes.count() == 0:
                                 print("Unable to find this ingredient: " +
                                       ing_data['name'])
                             elif products.count() + recipes.count() > 1:
                                 exact_match_found = False
                                 for p in products:
                                     if str(p) == ing_data['name']:
                                         food = p
                                         exact_match_found = True
                                 for r in recipes:
                                     if str(r) == ing_data['name']:
                                         food = r
                                         exact_match_found = True
                                 if not exact_match_found:
                                     print(
                                         "It's unclear which Product or Recipe was meant for this ingredient."
                                     )
                                     print("There were these options:")
                                     for p in products:
                                         print("- " + str(p))
                                     for r in recipes:
                                         print("- " + str(r))
                                     print(
                                         "Please change the 'name' so that only one of these is found."
                                     )
                                     continue
                             else:
                                 if products.count() == 1:
                                     food = products.all()[0]
                                 else:
                                     food = recipes.all()[0]
                             try:
                                 amount = float(ing_data['amount'])
                             except ValueError:
                                 continue
                             ingredient_query = Ingredient.objects.filter(
                                 recipe=recipe,
                                 amount=amount,
                                 product=food
                                 if type(food) is Product else None,
                                 food_is_recipe=food
                                 if type(food) is Recipe else None)
                             if ingredient_query.count() == 1:
                                 ingredient = ingredient_query[0]
                                 print("Found existing Ingredient: \"" +
                                       str(ingredient) + "\" for Recipe: " +
                                       str(ingredient.recipe))
                             else:
                                 ingredient = Ingredient(recipe=recipe,
                                                         amount=amount)
                                 ingredient.food = food
                                 ingredient.save()
                                 print("Added Ingredient: \"" +
                                       str(ingredient) + "\" for Recipe: " +
                                       str(ingredient.recipe))
                 if 'model' in data and data['model'] == 'backend.Ingredient' and 'fields' in data and \
                         'recipe' in data['fields'] and 'amount' in data['fields'] and \
                         ('food' in data['fields'] or
                          'product' in data['fields'] or
                          'food_is_recipe' in data['fields']):
                     fields = data['fields']
                     try:
                         amount = float(fields['amount'])
                     except ValueError:
                         continue
                     recipe = None
                     for r in recipe_table:
                         if fields['recipe'] == r['fixture_pk']:
                             recipe = r['real_recipe']
                     food = None
                     if 'food' in fields:
                         for p in product_table:
                             if fields['food'][0] == '0' and fields['food'][
                                     1:] == p['fixture_pk']:
                                 food = p['real_product']
                         for r in recipe_table:
                             if fields['food'][0] == '1' and fields['food'][
                                     1:] == r['fixture_pk']:
                                 food = r['real_recipe']
                     if 'product' in fields:
                         for p in product_table:
                             if fields['product'] == p['fixture_pk']:
                                 food = p['real_product']
                     if 'food_is_recipe' in fields:
                         for r in recipe_table:
                             if fields['food_is_recipe'] == r['fixture_pk']:
                                 food = r['real_recipe']
                     if recipe is None or food is None:
                         continue
                     ingredient_query = Ingredient.objects.filter(
                         recipe=recipe,
                         amount=amount,
                         product=food if type(food) is Product else None,
                         food_is_recipe=food
                         if type(food) is Recipe else None)
                     if ingredient_query.count() != 1:
                         new_ingredient = Ingredient(recipe=recipe,
                                                     amount=amount)
                         new_ingredient.food = food
                         new_ingredient.save()
                         print("Added Ingredient: \"" +
                               str(new_ingredient) + "\" for Recipe: " +
                               str(new_ingredient.recipe))
                     else:
                         print("Ingredient: \"" + str(ingredient_query[0]) +
                               "\" for Recipe: " +
                               str(ingredient_query[0].recipe) +
                               " was already in the database.")
예제 #16
0
from backend import db
from backend.models import Customer, Product, Invoice_product, Invoice

db.create_all()

c1 = Customer('Jing')
c2 = Customer('Lisa')
c3 = Customer('Larry')

p1 = Product('apple', 10)
p2 = Product('orange', 13)
p3 = Product('cherry', 50)

Ip1 = Invoice_product(1, 3)
Ip2 = Invoice_product(2, 2)
Ip3 = Invoice_product(3, 1)
Ip4 = Invoice_product(3, 2)
Ip5 = Invoice_product(3, 3)

Inv1 = Invoice(1, '2019-03-01')
Inv2 = Invoice(2, '2019-04-01')
Inv3 = Invoice(3, '2019-05-01')

db.session.add_all(
    [c1, c2, c3, p1, p2, p3, Ip1, Ip2, Ip3, Ip4, Ip5, Inv1, Inv2, Inv3])

db.session.commit()

print(db)
# # Import database info
# from invoice_app import db, Line_Item, Invoice, Product, Customer
예제 #17
0
파일: views.py 프로젝트: Levitron/Nutria-DB
def save_food(request):
    if request.method != 'POST':
        return HttpResponseBadRequest(
            '{"error": "You have to save data via POST."}',
            content_type="application/json")
    try:
        data = json.loads(request.body)
    except json.JSONDecodeError:
        return HttpResponseBadRequest(
            '{"error": "The body of your POST request is not valid JSON."}',
            content_type="application/json")
    if 'token' not in data or 'food' not in data:
        return HttpResponseBadRequest(
            '{"error": "Please supply a \'token\' and the \'food\' to save."}',
            content_type="application/json")
    try:
        token_payload = jwt.decode(data['token'], JWT_SECRET, 'HS256')
    except jwt.InvalidSignatureError:
        return HttpResponseBadRequest(
            '{"error": "Invalid signature of the authentication token."}',
            content_type="application/json")
    except jwt.ExpiredSignatureError:
        return HttpResponseBadRequest(
            '{"error": "This authentication token is expired. ' +
            'Please log in again and get a new token."}',
            content_type="application/json")
    except jwt.InvalidTokenError:
        return HttpResponseBadRequest(
            '{"error": "Invalid authentication token."}',
            content_type="application/json")
    try:
        user = User.objects.get(pk=token_payload['id'])
    except User.DoesNotExist:
        return HttpResponseBadRequest(
            '{"error": "Could not find the user for this token. Was it deleted?"}',
            content_type="application/json")
    if not user:
        return HttpResponseBadRequest(
            '{"error": "Could not find the user with id=' +
            token_payload['id'] + '. Was it deleted?"}',
            content_type="application/json")
    food_dict = data['food']
    if 'name' not in food_dict:
        return HttpResponseBadRequest(
            '{"error": "Please supply at least a \'name\' for each food item."}',
            content_type="application/json")
    category, name_addition = split_name(food_dict['name'])
    try:
        cat = Category.objects.get(name=category)
    except Category.DoesNotExist:
        return HttpResponseBadRequest(json.dumps({
            "error":
            category +
            ' is not a valid category. All valid categories are listed in this error.',
            "categories": [c.name for c in Category.objects.all()]
        }),
                                      content_type="application/json")
    if 'ingredients' in food_dict and 'ean' not in food_dict:
        food = Recipe(category=cat, name_addition=name_addition, author=user)
        ingredient_list = []
        for ingredient in food_dict['ingredients']:
            if ingredient['food'][0] == '0':
                food_class = Product
            elif ingredient['food'][0] == '1':
                food_class = Recipe
            else:
                return HttpResponseBadRequest(json.dumps({
                    "error":
                    "The id begins with " + ingredient['food'][0] +
                    " which is an unknown type."
                }),
                                              content_type="application/json")
            try:
                ingredient_food = food_class.objects.get(
                    pk=int(ingredient['food'][1:]))
            except food_class.DoesNotExist:
                return HttpResponseBadRequest(json.dumps({
                    "error":
                    "There is no " + str(food_class.__name__) +
                    " with the id " + ingredient['food'] + "!"
                }),
                                              content_type="application/json")
            try:
                amount = float(ingredient['amount'])
            except ValueError:
                return HttpResponseBadRequest(json.dumps({
                    "error":
                    "The amount you gave for the " + food_class.__name__ +
                    " " + str(ingredient_food) + "(id: " + ingredient['food'] +
                    ") is not a number."
                }),
                                              content_type="application/json")
            ingredient_list.append({'food': ingredient_food, 'amount': amount})
        food.save()
        for ingredient in ingredient_list:
            i = Ingredient(recipe=food, amount=ingredient['amount'])
            i.food = ingredient['food']
            i.save()
        if 'servings' in food_dict and len(food_dict['servings']) >= 1:
            for serving in food_dict['servings']:
                if 'name' in serving and type(
                        serving['name']) is str and 'size' in serving:
                    try:
                        new_serving = Serving(name=serving['name'],
                                              size=float(serving['size']))
                        new_serving.food = food
                        new_serving.save()
                    except ValueError:
                        return HttpResponseBadRequest(
                            '{"error": "The recipe was saved but the serving '
                            + serving['name'] + ' could not be saved. ' +
                            'This was because its size was not a number. ' +
                            'All serving sizes must be a floats (in g)."}',
                            content_type="application/json")
                else:
                    return HttpResponseBadRequest(
                        '{"error": "The recipe was saved but at least ' +
                        'one serving could not be saved. ' +
                        'Servings need a name (string) and a size in g."}',
                        content_type="application/json")
        return HttpResponse('{"success": "Recipe successfully added."}',
                            content_type="application/json")
    elif all(k in food_dict for k in ['calories', 'reference_amount']):
        try:
            food = Product(category=cat,
                           name_addition=name_addition,
                           author=user,
                           calories=float(food_dict['calories']),
                           reference_amount=float(
                               food_dict['reference_amount']))
        except ValueError:
            return HttpResponseBadRequest(
                '{"error": "Either the calories or the reference amount are no float '
                + 'values. Please supply floats."}',
                content_type="application/json")
        if 'ean' in food_dict:
            food.ean = convert_digits_to_bytes(food_dict['ean'])
        for element in [
                'total_fat', 'saturated_fat', 'cholesterol', 'protein',
                'total_carbs', 'sugar', 'dietary_fiber', 'salt', 'sodium',
                'potassium', 'copper', 'iron', 'magnesium', 'manganese',
                'zinc', 'phosphorous', 'sulphur', 'chloro', 'fluoric',
                'vitamin_b1', 'vitamin_b12', 'vitamin_b6', 'vitamin_c',
                'vitamin_d', 'vitamin_e'
        ]:
            if element in food_dict:
                try:
                    food.__setattr__(element, float(food_dict[element]))
                except ValueError:
                    return HttpResponseBadRequest(
                        '{"error": "The amount of ' + element +
                        ' must be a float."}',
                        content_type="application/json")
        food.save()
        if 'servings' in food_dict and len(food_dict['servings']) >= 1:
            for serving in food_dict['servings']:
                if 'name' in serving and type(
                        serving['name']) is str and 'size' in serving:
                    try:
                        new_serving = Serving(name=serving['name'],
                                              size=float(serving['size']),
                                              product=food)
                        new_serving.save()
                    except ValueError:
                        return HttpResponseBadRequest(
                            '{"error": "The product was saved but the serving '
                            + serving['name'] + ' could not be saved. ' +
                            'This was because its size was not a number. ' +
                            'All serving sizes must be a floats (in g)."}',
                            content_type="application/json")
                else:
                    return HttpResponseBadRequest(
                        '{"error": "The product was saved but at least ' +
                        'one serving could not be saved. ' +
                        'Servings need a name (string) and a size in g."}',
                        content_type="application/json")
        return HttpResponse('{"success": "Product successfully added."}',
                            content_type="application/json")
    else:
        return HttpResponseBadRequest(
            '{"error": "You supplied data for a product but it misses a reference '
            +
            'amount or calorie count. Please make sure the \'calories\' and ' +
            '\'reference_amount\' fields are present. If you wanted to save a '
            + 'recipe you have to supply a list of ingredients."}',
            content_type="application/json")
예제 #18
0
 def testRecipeSetProperties(self):
     author = User(username='******', password='******')
     author.save()
     cat = Category(name='test')
     cat.save()
     r = Recipe(category=cat, name_addition='recipe', author=author)
     r.save()
     a = Product(category=cat,
                 name_addition='a',
                 author=author,
                 reference_amount=100.0,
                 calories=100.0)
     a.save()
     b = Product(category=cat,
                 name_addition='b',
                 author=author,
                 reference_amount=100.0,
                 calories=20.0)
     b.save()
     i1 = Ingredient(recipe=r, amount=100.0)
     i1.food = a
     i1.save()
     i2 = Ingredient(recipe=r, amount=200.0)
     i2.food = b
     i2.save()
     self.assertAlmostEqual(r.calories, 140, 5)
     r.calories = 280
     self.assertAlmostEqual(r.calories, 280, 5)
     self.assertAlmostEqual(r.ingredients.all()[0].amount, 200, 5)
     self.assertAlmostEqual(r.ingredients.all()[1].amount, 400, 5)
     r.total_fat = 1
     r.saturated_fat = 1
     r.cholesterol = 1
     r.protein = 1
     r.total_carbs = 1
     r.sugar = 1
     r.dietary_fiber = 1
     r.salt = 1
     r.sodium = 1
     r.potassium = 1
     r.copper = 1
     r.iron = 1
     r.magnesium = 1
     r.manganese = 1
     r.zinc = 1
     r.phosphorous = 1
     r.sulphur = 1
     r.chloro = 1
     r.fluoric = 1
     r.vitamin_b1 = 1
     r.vitamin_b12 = 1
     r.vitamin_b6 = 1
     r.vitamin_c = 1
     r.vitamin_d = 1
     r.vitamin_e = 1
     props = [
         'total_fat', 'saturated_fat', 'cholesterol', 'protein',
         'total_carbs', 'sugar', 'dietary_fiber', 'salt', 'sodium',
         'potassium', 'copper', 'iron', 'magnesium', 'manganese', 'zinc',
         'phosphorous', 'sulphur', 'chloro', 'fluoric', 'vitamin_b1',
         'vitamin_b12', 'vitamin_b6', 'vitamin_c', 'vitamin_d', 'vitamin_e'
     ]
     for prop in props:
         a.__setattr__(prop, 3)
         b.__setattr__(prop, 10)
     a.save()
     b.save()
     for prop in props:
         self.assertAlmostEqual(r.__getattribute__(prop), 46, 5)
     for prop in props:
         r.__setattr__(prop, 23)
         for prop2 in props:
             self.assertAlmostEqual(r.__getattribute__(prop2), 23, 5)
             self.assertAlmostEqual(r.ingredients.all()[0].amount, 100, 5)
             self.assertAlmostEqual(r.ingredients.all()[1].amount, 200, 5)
         r.__setattr__(prop, 46)
         for prop2 in props:
             self.assertAlmostEqual(r.__getattribute__(prop2), 46, 5)
             self.assertAlmostEqual(r.ingredients.all()[0].amount, 200, 5)
             self.assertAlmostEqual(r.ingredients.all()[1].amount, 400, 5)
예제 #19
0
    apple = Category(name='apple')
    women = Category(name='women')
    gaming = Category(name='gaming')
    kitchen = Category(name='kitchen')

    db.session.add_all(
        [electronics, tv, men, fashion, apple, women, gaming, kitchen])

    # men fashion
    for product in response_one_JSON["products"]:
        db.session.add(
            Product(name=product["title"],
                    description="comfortable everyday wear",
                    price=product["price"]["current_price"],
                    before_price=product["price"]["before_price"],
                    img_url=product["thumbnail"],
                    prime=product["amazonPrime"],
                    total_reviews=product["reviews"]["total_reviews"],
                    rating=product["reviews"]["rating"],
                    categories=[men, fashion]))

    # women fashion
    for product in response_two_JSON["products"]:
        db.session.add(
            Product(name=product["title"],
                    description="comfortable everyday wear",
                    price=product["price"]["current_price"],
                    before_price=product["price"]["before_price"],
                    img_url=product["thumbnail"],
                    prime=product["amazonPrime"],
                    total_reviews=product["reviews"]["total_reviews"],
예제 #20
0
 def testRecipeCalculations(self):
     author = User(username='******', password='******')
     author.save()
     cat = Category(name='test')
     cat.save()
     a = Product(category=cat,
                 name_addition='a',
                 author=author,
                 reference_amount=100.0,
                 calories=100.0)
     a.protein = 30.0
     a.save()
     b = Product(category=cat,
                 name_addition='b',
                 author=author,
                 reference_amount=100.0,
                 calories=20.0)
     b.save()
     r = Recipe(category=cat, name_addition='recipe', author=author)
     r.save()
     i1 = Ingredient(recipe=r, amount=10.0)
     i1.food = a
     i2 = Ingredient(recipe=r, amount=200.0)
     i2.food = b
     i1.save()
     i2.save()
     # Recipe created
     self.assertAlmostEqual(r.calories, 50.0, 5)
     self.assertIsNone(r.protein)
     b.protein = 10.0
     b.save()
     self.assertAlmostEqual(r.protein, 23.0, 5)