コード例 #1
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)
コード例 #2
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)
コード例 #3
0
ファイル: load_cat.py プロジェクト: shpeeck/wezom
    def handle(self, *args, **options):
        print('Start')
        Category.objects.all().delete()
        Subcategory.objects.all().delete()

        session = HTMLSession()
        resp = session.get('http://west-info.ua/katalog-predpriyatij/')
        a = 1

        while True:
            b = 1
            try:
                links = resp.html.xpath(
                    f'/html/body/header/div[3]/div/nav/ul/li[2]/ul/li[{a}]/a/text()'
                )
                print('Категория: {}'.format(links[0]))
                cat = Category()
                cat.name = links[0]
                cat.save()
                while True:
                    try:
                        links = resp.html.xpath(
                            f'/html/body/header/div[3]/div/nav/ul/li[2]/ul/li[{a}]/ul/li[{b}]/a/text()'
                        )
                        print('Подкатегория -- {}'.format(links[0]))
                        sub = Subcategory()
                        sub.name = links[0]
                        sub.category = cat
                        sub.save()
                        b += 1
                    except:
                        break
                a += 1
            except:
                break
コード例 #4
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)
コード例 #5
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)
コード例 #6
0
    def upload_file(self, arguments):
        file_dict = request.files.to_dict()
        if not file_dict:
            return self.is_fail('no image file')
        for k, v in file_dict.items():
            if v.mimetype.split('/')[0] != 'image':
                return self.is_fail('upload file type is not image')
        output_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                  'static/upload')
        url_list = []
        for key, file in file_dict.items():
            suffix = file.filename.split('.')[-1]
            filename = str(uuid.uuid1()) + '.' + suffix
            file.save(os.path.join(output_dir, filename))
            url_list.append(filename)

        uid = current_user['id']
        arguments.update({'uid': uid, 'url_address': pickle.dumps(url_list)})
        new_menu = Menu(**arguments)
        result = new_menu.save()

        # check whether there is a new type
        menu_type = arguments['type']
        category_list = Category.get_categories('uid')
        if menu_type not in category_list:
            category_list.append(menu_type)
            Category.update(
                {
                    'uid': uid,
                    'category': pickle.dumps(category_list)
                }, ['uid'])
        return self.is_done(result)
コード例 #7
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)
コード例 #8
0
ファイル: views.py プロジェクト: ajaxj/djmv
def categoryadd(request):
    if request.method == "POST":
        _name = request.POST['name']
        _cname = request.POST['cname']
        category = Category()
        category.name = _name
        category.cname = _cname
        category.save()
        return HttpResponseRedirect("/backend/categories")
    else:
        return render_to_response("backend/categoryadd.html",None,context_instance=RequestContext(request))
コード例 #9
0
    def testIngredientNoFood(self):
        def set_food(i, food):
            i.food = food

        author = User(username='******', password='******')
        author.save()
        cat = Category(name='test')
        cat.save()
        r = Recipe(category=cat, name_addition='recipe', author=author)
        r.save()
        i = Ingredient(recipe=r, amount=10.0)
        self.assertRaises(NoFoodException, set_food, i, cat)
コード例 #10
0
ファイル: views.py プロジェクト: geekone/mitiyu
def category_add(request):
    if request.method == "POST":
        form = CategoryForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            category = Category()
            category.name = cd['name']
            category.save()
            return HttpResponseRedirect("/backend/categories")
    else:
        form = CategoryForm()
        c = {'form':form}
        return render_to_response("backend/category_add.html",c,context_instance=RequestContext(request))
コード例 #11
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")
コード例 #12
0
 def test_get_quizzes_with_results(self):
     category = Category.query.first()
     res = self.client().post('/quizzes',
                              json={'previous_questions': [], 'quiz_category': Category.format(category)})
     data = json.loads(res.data)
     self.assertEqual(res.status_code, 200)
     self.assertTrue(data['success'])
     self.assertEqual(len(data['previous_questions']), 1)
コード例 #13
0
    def post(self, request):
        category_id = request.POST.get("category_id")

        category = Category.get_by_id(category_id)

        if category is not None:
            category.delete()

        return redirect(reverse('backend.category.index'))
コード例 #14
0
    def test_get_quizzes_with_wrong_category(self):
        category = Category.query.first()
        category.id = 12
        res = self.client().post('/quizzes',
                                 json={'previous_questions': [], 'quiz_category': Category.format(category)})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['error'], 422)
        self.assertEqual(data['message'], 'Unprocessable Entity')
        self.assertEqual(data['success'], False)
コード例 #15
0
    def test_get_question_by_category_with_results(self):
        res = self.client().get('/categories/1/questions')
        data = json.loads(res.data)

        category = Category.query.first()

        self.assertEqual(res.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(len(data['questions']), 5)
        self.assertEqual(data['total_questions'], 5)
        self.assertEqual(data['currentCategory'], Category.format(category))
コード例 #16
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "trivia_test"
        self.database_path = "postgres://{}/{}".format('localhost:5432', self.database_name)
        setup_db(self.app, self.database_path)

        self.new_question = {
            'category': '1',
            'question': 'Neil Gaiman',
            'answer': 'aaaaaaa',
            'difficulty': 5
        }
        self.new_category = {
            'id': '1',
            'type': 'test_type',
        }
        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy(self.app)
            self.db.init_app(self.app)
            self.db.create_all()


            # # create all tables

            # create all tables
            self.question = Question(difficulty=self.new_question['difficulty'],
                                     question=self.new_question['question'],
                                     answer=self.new_question['answer'], category=self.new_question['category'])
            self.question.insert()

            if Category.query.first() is None:
                category = Category(type=self.new_category['type'])
                category.insert()
コード例 #17
0
def add_new_category():
    """Adds a new category to the database

    Method Type: POST

    Special Restrictions
    --------------------
    User must be logged in
    User must be admin

    JSON Parameters
    ---------------
    auth_token : str
        Token to authorize the request - released when logging in
    cat_name : str
        Name of the category to be added
    cat_level : int
        Level of the category you want to add
    cat_ideal_num : int
        Ideal number to be reached

    Returns
    -------
    JSON
        status : int
            Tells whether or not did the function work - 1 for success, 0 for failure
    """
    request_json = request.get_json()

    auth_token = request_json['auth_token']
    user = User.verify_auth_token(auth_token)

    if user is None:
        return json.dumps({'status': 0, 'error': "User Not Authenticated"})

    if not user.isAdmin:
        return json.dumps({'status': 0, 'error': "Access Denied"})

    cat_name = request_json['cat_name']
    cat_level = request_json['cat_level']
    cat_ideal_num = request_json['cat_ideal_num']
    new_cat = Category(name=cat_name, level=cat_level, ideal_num=cat_ideal_num)
    db.session.add(new_cat)
    db.session.commit()

    return json.dumps({'status': 1})
コード例 #18
0
 def post(self, args):
     """
     创建新分类
     :param args:
     :return:
     """
     category = Category(name=args['name'])
     try:
         db.session.add(category)
         db.session.commit()
     except Exception as e:
         db.session.rollback()
         current_app.logger.error(e)
         return api_abort(400, "数据保存失败")
     response = jsonify(category_schema(category))
     response.status_code = 201
     return response
コード例 #19
0
with app.app_context():
  db.drop_all()
  db.create_all()

  demo = User(username = '******', email = '*****@*****.**', avatar_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcThQUnhWZqYrbaRtrvH6uUJxiF64UMXBWO3XQ&usqp=CAU', hashed_password = generate_password_hash("password"))
  palpatine = User(username = '******', email = '*****@*****.**', avatar_url = 'https://pm1.narvii.com/6989/837a8e36313c4a026a2f5acb9fe0a9f255d93a92r1-1080-1920v2_hq.jpg')
  anakin = User(username = '******', email = '*****@*****.**', avatar_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcR_sDERiegE5BSNiwpioOjCt5ndx89W1t4XNw&usqp=CAU')
  jabba = User(username = '******', email = '*****@*****.**', avatar_url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Jabba_the_Hutt.jpg/498px-Jabba_the_Hutt.jpg')
  tarkin = User(username = '******', email = '*****@*****.**', avatar_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQ633qJmSKAVdZul4oWR-f9wB6US_N_bHee2g&usqp=CAU')
  dooku = User(username = '******', email = '*****@*****.**', avatar_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQALITa_iwn6z77Xr6RMHDJG-0l8pvFYI--tA&usqp=CAU')
  boba = User(username = '******', email = '*****@*****.**', avatar_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTYj2Rw2Crz24sNcXZ9v9KfnlEZupa_ZdmMKQ&usqp=CAU')
  han = User(username = '******', email = '*****@*****.**', avatar_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTS9TwNUBH0EbzmUt6OWZ4XhjIsiIQ84jf3tg&usqp=CAU')
  luke = User(username = '******', email = '*****@*****.**', avatar_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSczQtK1E0AgyUchH_Ov7hj5xHnQr69LT7O2g&usqp=CAU')
  rey = User(username = '******', email = '*****@*****.**', avatar_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQe0sZYKoaf065ZKjnl4G1qy1qCB6p8CNhQpw&usqp=CAU')

  party = Category(type = 'Surprise Party')
  production = Category(type = 'Live Productions')
  exectution = Category(type = 'Live Executions')
  sport = Category(type = 'Sports')
  tour = Category(type = 'Tours')
  launch = Category(type = 'Product Launches')
  seminar = Category(type = 'Seminars')

  order_66 = Event(name = 'Order 66', event_description = 'Enjoy a fun night at the Jedi Temple! We will all meet outside on the front steps, and then go in and surprise all the younglings!', host_id = 3, event_date = 'May 27, 19BBY @ 21:00', event_planet = 'Corusant', event_picture_url = 'https://i.ytimg.com/vi/lBbQg8r8tdc/maxresdefault.jpg', category_id =  1, is_featured = True)
  podrace = Event(name = 'Boonta Eve Podrace', event_description = 'This is the biggest podrace of the year! Held in and around the Grand Arena in Mos Epa, this is bound to be a race you will not want to miss! Sebabulba is once again gavored to win the race. **Upgrade your ticket to sit with the Tuskan Raiders and try to shoot down the Racers!**', host_id = 4, event_date = '15:00 hours, June 12, 32BBY', event_planet = 'Tatooine', event_picture_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQoXdjeOE8nKrEu-jWNxg-nCeDGOPjBJXGbkA&usqp=CAU', category_id = 4, is_featured = True)
  death_star = Event(name = 'Death Star Unvieling', event_description = 'Take a trip to the lovely planet of Alderaan, located in the Core Worlds. This planet has many famous people including the Orengas. You will get a front row introduction to the Empires new luxury cruise ship, called the Death Star. It is a state of the art cruise liner that will travel all over the galaxy under control of the great captain Govenor Tarkin.', host_id = 5, event_date = '0:00 hours January 1, 0BBY', event_planet = 'Alderaan', event_picture_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSFhGRKvL6ZzQAaN-goNpxqwbulV6VFQ1Or1g&usqp=CAU', category_id = 6, is_featured = True)
  geonosis_execution = Event(name = 'Republic Leaders Execution', event_description = 'The evil Senator Amidala and the Jedis Skywalker and Kenobi have been caught!!!!! Their executions have been schedule to be held in the Petranaki Arena. Buy tickets to this execution. 3 high ranking Republic members! Once in a lifetime event!', host_id = 6, event_date = '17:00 hours, June 22, 19BBY', event_planet = 'Geonosis', event_picture_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSELfkGG_qoGhokNwcwmwSMR5ThNkXXM5iLyA&usqp=CAU', category_id = 3, is_featured = True)
  carbonite = Event(name = 'Carbonite Museum Grand Opening', event_description = 'Come to Cloud City in Bespin for the Grand Opening of the Carbonite Museum! For one night only, our main attraction is the notorious smuggler Han Solo.', host_id = 7, event_date = '20:00 hours, August 12, 3ABY', event_planet = 'Bespin', event_picture_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTqMzZ4SePebMG1Ff1VM2LVSC_mMCdG_FnVTR6G2eHidEV0RmeGX3Tn8sQpdQ&usqp=CAc', category_id = 5, is_featured = True)
  darth_plagueis = Event(name = 'Squid Lake by the Mon Calamari Ballet at Coruscant Opera House', event_description = 'In the beautiful Uscru District, lies the Wonderful Galaxies Opera House. The Galaxy renound Mon Calamarin Ballet is putting on a production of Squid Lake. If you have never seen a ballet, this is the one to attend! **Upgrade your tickets to sit in the box with Chancellor Palpentine. Who knows, maybe you will learn things the Jedi can\'t teach you!**', host_id = 2, event_date = '21:00 hours, February 1 19BBY', event_planet = 'Corusant', event_picture_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSWqj-k_7il4cl1r1vfVfACzbntLKR9NEGVcA&usqp=CAU', category_id = 2, is_featured = True)
  kessel = Event(name = 'Kessel Run Tour', event_description = 'Join the legendary smuggler Han Solo on his tour of the Kessel Run! Ride in the Millenium Falcon, flown by Han Solo and his partner Chewie. The tour starts on Kessel and ends sourth of the Si\'Flaata Cluster. The gole is to move spice without getting caught by Imperial Ships. Good Luck and have fun!', host_id = 8, event_date = 'October 27, 10BBY @ 11:00', event_planet = 'Kessel', event_picture_url = 'https://www.thathashtagshow.com/wp-content/uploads/2020/03/chewie-falcon-4.jpg', category_id = 5, is_featured = True)
  jedi = Event(name = 'Seminar at the Jedi Academy', event_description = 'Get a free lesson in exploring the force led by the one and only Luke Skywalker! The man who brought down the Empire. Open to all beings, even if you are not force sensitive. Surprise guests may include Jedi Ghosts!', host_id = 9, event_date = 'July 12, 23ABY @ 12:00', event_planet = 'Corusant', event_picture_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTZsvsoLWSwy8jxWt21XbIke_y6rKzHkB6zqw&usqp=CAU', category_id = 7, is_featured = True)
コード例 #20
0
response_five_JSON = response_five.json()
response_six = requests.request("GET",
                                url,
                                headers=headers,
                                params=querystring_six)
response_six_JSON = response_six.json()

# aps iphone, fashion women, fashion men, aps tv, aps xbox, aps kitchen

# print(response.text)

with app.app_context():
    db.drop_all()
    db.create_all()

    electronics = Category(name='electronics')
    tv = Category(name='tv')
    men = Category(name='men')
    fashion = Category(name='fashion')
    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"],
コード例 #21
0
ファイル: initial_data.py プロジェクト: pinae/Nutria-DB
 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.")
コード例 #22
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)