Ejemplo n.º 1
0
def create_foods(count_by_shop=20, rate_extra=RATE_EXTRA_CREATION):
    count_by_shop_extra = int(math.floor(count_by_shop * rate_extra) + 1)
    shops = Shop.query.all()
    foods = []
    for shop in shops:
        foods_choice = random.sample(fixtures_data.foods, count_by_shop)
        foods_extra_choice = random.sample(fixtures_data.foods_extra,
                                           count_by_shop_extra)
        price_choice = [
            round((random.random() * MAX_PRICE) + MAX_PRICE, 2)
            for _ in range(count_by_shop)
        ]
        price_extra_choice = [
            round((random.random() * MAX_PRICE) + MAX_PRICE, 2)
            for _ in range(count_by_shop_extra)
        ]

        for i in range(count_by_shop):
            food = Food(name=foods_choice[i],
                        price=price_choice[i],
                        extra=False,
                        shop=shop)
            foods.append(food)
        for i in range(count_by_shop_extra):
            food = Food(name=foods_extra_choice[i],
                        price=price_extra_choice[i],
                        extra=True,
                        shop=shop)
            foods.append(food)

    db.session.add_all(foods)
    db.session.commit()
Ejemplo n.º 2
0
 def test_food_repr(self):
     u = push_dummy_user()
     list_ = push_dummy_list(u, 'List')
     a = Food(list_id=list_.id, name='Food')
     db.session.add(a)
     db.session.commit()
     self.assertEqual(a.__repr__(), '<Food Food of List List>')
Ejemplo n.º 3
0
def post_foods(list_id):
    req = request.get_json()
    if not req:
        raise APIError("application/json is required")
    if "name" not in req:
        raise APIError("name is required")
    list_ = List.query.filter_by(id=list_id).first()
    if Food.query.filter_by(name=req["name"], list_id=list_.id).first():
        raise APIError(f'Food {req["name"]} already exists')
    food = Food(list_id=list_.id, name=req["name"])
    db.session.add(food)
    db.session.commit()
    json_obj = [food.to_dict() for food in list_.foods]
    return jsonify(json_obj), 201
Ejemplo n.º 4
0
def set(id):
    food = None
    if id:
        food = Food.query.get_or_404_deleted(id, msg='找不到指定商品')
    cat_list = FoodCat.query.all()
    if request.method == 'POST':
        form = SetForm().validate()
        with db.auto_commit():
            if not food:
                food = Food()
            stock_ago = food.stock or 0
            food.set_attrs(form.data)
            db.session.add(food)
        FoodStockChangeLog.set_stock_change_log(food.id, stock_ago, food.stock, '后台修改')
        return Success()
    return render_template('food/set.html', info=food, cat_list=cat_list, current='index')
Ejemplo n.º 5
0
def quickadd(date=datetime.now().strftime('%B %d, %Y'), meal=None):
    user = User.query.filter_by(id=current_user.get_id()).first()
    form = QuickAddCals()

    if request.method == 'GET':
        return render_template('quickadd.html', user=user, form=form)

    if request.method == 'POST':
        try:
            float(form.calories.data)
            float(form.carbs.data)
            float(form.fat.data)
            float(form.protein.data)
        except:
            flash("Please enter valid numbers.")
        else:
            food = Food(food_name='Quick Add',
                        count=1,
                        kcal=form.calories.data,
                        protein=form.protein.data,
                        fat=form.fat.data,
                        carbs=form.carbs.data,
                        unit='',
                        meal=meal,
                        date=date,
                        ndbno=-1,
                        user_id=current_user.get_id())
            db.session.add(food)
            db.session.commit()
        return redirect(url_for('diary', date_pick=date))
    def test_get_category_by_food(self):
        u = push_dummy_user()
        push_dummy_list(u, 'TestyList')
        with self.test_client:
            self.login(u.username)

            rsp = self.test_client.get('/api/foods/1/categories')
            self.assertEqual(rsp.status, '404 NOT FOUND')

            list_ = List.query.first()
            food = Food(list_id=list_.id, name='Food')
            db.session.add(food)
            db.session.commit()

            rsp = self.test_client.get('/api/foods/1/categories')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [])

            foodcat = FoodCategory(list_id=list_.id, name='Cat')
            db.session.add(foodcat)
            db.session.commit()
            foodcatass = FoodCategoryAssociation(food_id=food.id,
                                                 category_id=foodcat.id)
            db.session.add(foodcatass)
            db.session.commit()

            rsp = self.test_client.get('/api/foods/1/categories')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [{'id': 1, 'name': 'Cat'}])
Ejemplo n.º 7
0
def foodAdd():
    name = request.values['food']
    cate_id = request.values['cate_id']

    if cate_id == '0':
        result = json_response(201, '菜系不存在')
        return jsonify(result)

    try:
        food = Food.query.filter_by(name=name, cate_id=cate_id).first()
    except Exception as e:
        print(e)

    # 如果已经存在
    if food:
        result = json_response(201, '该美食已经存在')
    else:
        # 如果不存在,写入food表
        food = Food(
            name=name,
            cate_id=cate_id
        )
        db.session.add(food)
        db.session.commit()

        result = json_response()

    return jsonify(result)
def confirm_food():
    """
        User confirms food and it gets added to database

        expects:
        {
            username: <Username> (used for authentification),
            date_consumed: <Data when food was consumed> (fromat: DD/MM/YY),
            payload: <Data that was sent to confirm>
        }

    """
    data = request.get_json()
    user = User.query.filter_by(username=data["user"]).first()
    if user:
        food = Food(name=data["data"]["name"], date_consumed=data["date_consumed"], calories=data["data"]["nutrition"]["calories"], fat=data["data"]["nutrition"]["total_fat"], protein=data["data"]["nutrition"]["protein"], sugar=data["data"]["nutrition"]["sugars"], carbs=data["data"]["nutrition"]["total_carb"], sodium=data["data"]["nutrition"]["sodium"], consumer=user)
        db.session.add(food)
        db.session.commit()
        return jsonify(
            message="Food added successfully"
        ), 200
    else:
        return jsonify(
            message="Not Authorized"
        ), 401
Ejemplo n.º 9
0
def food_add():
    """
    添加菜品页面
    """
    form = FoodForm() # 实例化form表单
    form.cate_id.choices = [(v.id, v.name) for v in Category.query.all()] # 为cate_id添加属性
    if form.validate_on_submit():
        data = form.data
        # 判断菜品是否存在
        food_count = Food.query.filter_by(name=data["name"]).count()
        # 判断是否有重复数据。
        if food_count == 1 :
            flash("菜品已经存在!", "err")
            return redirect(url_for('admin.food_add'))

        # 为Scenic类属性赋值
        food = Food(
            name=data["name"],
            cate_id = data["cate_id"],
        )
        db.session.add(food)  # 添加数据
        db.session.commit()     # 提交数据
        flash("添加美食成功!", "ok") # 使用flash保存添加成功信息
        return redirect(url_for('admin.food_add')) # 页面跳转
    return render_template("admin/food_add.html", form=form) # 渲染模板
Ejemplo n.º 10
0
 def addfood(self):
     print 'add'
     if request.method == 'POST':
         print request.get_data()
         temp = Food(request.json['foodName'])
         db.session.add(temp)
         db.session.commit()
     return 'seccess'
Ejemplo n.º 11
0
    def set_up_test_db():
        person1 = Person(index=0, name='Test', age=30, has_died=False, eye_color='black', phone='000', address='test')
        person2 = Person(index=1, name='Test', age=30, has_died=False, eye_color='black', phone='000', address='test')
        friend = Person(index=2, name='Friend', age=30, has_died=False, eye_color='brown', phone='000', address='test')
        company = Company(index=0, name='Test')
        no_employees_company = Company(index=1, name='No Employees')
        vegetable = Food(index=0, name='Lettuce', type=Food.VEGETABLE)
        fruit = Food(index=1, name='Banana', type=Food.FRUIT)

        person1.company = company
        person1.foods.append(vegetable)
        person1.foods.append(fruit)
        person2.company = company
        person1.befriend(friend)
        person2.befriend(friend)

        db.session.add(person1)
        db.session.add(no_employees_company)
Ejemplo n.º 12
0
def index():
    form = AddFoodForm()
    if form.validate_on_submit():
        food = Food(name=form.name.data, food_type=form.food_type.data, user_id=current_user.id)
        db.session.add(food)
        db.session.commit()
        flash('{} added to your FRDJ'.format(form.name.data))
        return redirect(url_for('index'))
    foods = User.query.filter_by(username=current_user.username).first().get_food_list_by_type()
    return render_template('index.html', title='Home', form=form, foods=foods)
 def test_ingredient_repr(self):
     u = push_dummy_user()
     list_ = push_dummy_list(u, 'List')
     a = Food(list_id=list_.id, name='Food')
     db.session.add(a)
     db.session.commit()
     ing = Ingredient(food_id=a.id, name='Ingredient')
     db.session.add(ing)
     db.session.commit()
     self.assertEqual(ing.__repr__(),
                      '<Ingredient Ingredient of Food Food>')
Ejemplo n.º 14
0
 def test_food_to_dict(self):
     u = push_dummy_user()
     list_ = push_dummy_list(u, 'List')
     a = Food(list_id=list_.id, name='Food')
     db.session.add(a)
     db.session.commit()
     self.assertEqual(a.to_dict(), {
         'id': 1,
         'name': 'Food',
         'categories': []
     })
     cat = FoodCategory(list_id=list_.id, name='Cat')
     db.session.add(cat)
     db.session.commit()
     catass = FoodCategoryAssociation(food_id=a.id, category_id=cat.id)
     db.session.add(catass)
     db.session.commit()
     self.assertEqual(a.to_dict(), {
         'id': 1,
         'name': 'Food',
         'categories': [1]
     })
Ejemplo n.º 15
0
def foodAdd():
    name = request.values['food']
    cate_id = request.values['cate_id']
    food = Food.query.filter_by(name=name, cate_id=cate_id).first()
    # 如果已经存在
    if food:
        result = {"code": 201, "msg": '该美食已经存在'}
    else:
        # 如果不存在,写入food表
        food = Food(name=name, cate_id=cate_id)
        db.session.add(food)
        db.session.commit()
        result = {"code": 200, "msg": '添加成功'}
    return jsonify(result)
Ejemplo n.º 16
0
def home():
    if request.method == 'POST':
        try:
            food_content = request.form['content']
            new_food = Food(groceryName=food_content)        
            db.session.add(new_food)
            db.session.commit()
            return redirect('/')
        
        except:
            flash("thats already on the list")
            return redirect('/')
    else:
        foods = Food.query.order_by(Food.data_created).all()
        return render_template('home.html', foods = foods)
Ejemplo n.º 17
0
 def import_foods():
     app.logger.info('Importing foods...')
     e = ElementTree.parse('data/alim_2017-11-21.xml').getroot()
     for e_food in e.findall('ALIM'):
         group = Group.query.filter_by(id=int(e_food[5].text)).first()
         sgroup = SubGroup.query.filter_by(id=int(e_food[6].text)).first()
         ssgroup = SubSubGroup.query.filter_by(id=int(e_food[7].text)).first()
         food = Food(
             id=int(e_food[0].text),
             name_fr=' '.join(e_food[1].text.split()),
             name_en=' '.join(e_food[3].text.split()),
             group_id=group.id if group else None,
             sub_group_id=sgroup.id if sgroup else None,
             sub_sub_group_id=ssgroup.id if ssgroup else None
         )
         db.session.add(food)
     db.session.commit()
    def test_delete_category_by_food(self):
        u = push_dummy_user()
        push_dummy_list(u, 'TestyList')
        with self.test_client:
            self.login(u.username)

            list_ = List.query.first()
            food = Food(list_id=list_.id, name='Food')
            db.session.add(food)
            db.session.commit()

            foodcat = FoodCategory(list_id=list_.id, name='Cat')
            db.session.add(foodcat)
            db.session.commit()
            foodcatass = FoodCategoryAssociation(food_id=food.id,
                                                 category_id=foodcat.id)
            db.session.add(foodcatass)
            db.session.commit()

            rsp = self.test_client.get('/api/foods/1/categories')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [{'id': 1, 'name': 'Cat'}])

            rsp = self.test_client.delete('/api/foods/1/categories/1')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [])

            rsp = self.test_client.get('/api/foods/1/categories')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [])

            # re-delete same one
            rsp = self.test_client.delete('/api/foods/1/categories/1')
            self.assertEqual(rsp.status, '400 BAD REQUEST')

            # try to delete an id that doesn't exist
            rsp = self.test_client.delete('/api/foods/1/categories/10')
            self.assertEqual(rsp.status, '404 NOT FOUND')

            # non-existant-food
            rsp = self.test_client.delete('/api/foods/5/categories/1')
            self.assertEqual(rsp.status, '404 NOT FOUND')
    def test_post_category_by_food(self):
        u = push_dummy_user()
        push_dummy_list(u, 'TestyList')
        with self.test_client:
            self.login(u.username)

            rsp = self.test_client.get('/api/foods/1/categories')
            self.assertEqual(rsp.status, '404 NOT FOUND')

            list_ = List.query.first()
            food = Food(list_id=list_.id, name='Food')
            db.session.add(food)
            db.session.commit()

            rsp = self.test_client.get('/api/foods/1/categories')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [])

            foodcat = FoodCategory(list_id=list_.id, name='Cat')
            db.session.add(foodcat)
            db.session.commit()

            rsp = self.test_client.post('/api/foods/1/categories/1')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [{'id': 1, 'name': 'Cat'}])

            rsp = self.test_client.get('/api/foods/1/categories')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [{'id': 1, 'name': 'Cat'}])

            # re-post the same
            rsp = self.test_client.post('/api/foods/1/categories/1')
            self.assertEqual(rsp.status, '400 BAD REQUEST')

            # non-existant-category
            rsp = self.test_client.post('/api/foods/1/categories/10')
            self.assertEqual(rsp.status, '404 NOT FOUND')

            # non-existant-food
            rsp = self.test_client.post('/api/foods/5/categories/1')
            self.assertEqual(rsp.status, '404 NOT FOUND')
Ejemplo n.º 20
0
def search_food(local, name):
    # local = request.args.get('local', 'en', type=str)
    # name = request.args.get('name', type=str)
    page = request.args.get('page', 1, type=int)
    per_page = min(request.args.get('per_page', 10, type=int), 100)

    if local not in ['fr', 'en']:
        return bad_request('Wrong local, fr|en')
    attrib = Food.name_en if local == 'en' else Food.name_fr

    data = Food.to_collection_dict(
        Food.query.filter(attrib.like('%{}%'.format(name))),
        page,
        per_page,
        'api.search_food',
        local=local,
        name=name
    )

    return jsonify(data)
Ejemplo n.º 21
0
    def test_get_foods(self):
        u = push_dummy_user()
        push_dummy_list(u, 'TestyList')
        with self.test_client:
            self.login(u.username)
            rsp = self.test_client.get('/api/lists/1/foods')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [])

            list_ = List.query.first()
            db.session.add(Food(list_id=list_.id, name='Test'))
            db.session.commit()

            rsp = self.test_client.get('/api/lists/1/foods')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [{
                'id': 1,
                'name': 'Test',
                'categories': []
            }])
Ejemplo n.º 22
0
from app.models import User, Food
from app import db


#create User
try:
    user = User(username="******", name="Text", password_hash="123")
    db.session.add(user)
    db.session.commit()
    print("Create User successful")
except:
    print("Create User failed")

#add food
try:
    food = Food(name="Hot Dog", calories=280, fat=20, carbs=30, protein=10, sugar=5, sodium=10, consumer=user.user_id)
    db.session.add(food)
    db.session.commit()
    print("Add Food successful")
except:
    print("Add Food failed")
Ejemplo n.º 23
0
def get_nutrition(ndbno, meal=None, date=datetime.now()):

    form1 = AddToDiaryForm()

    search_url = "https://api.nal.usda.gov/ndb/nutrients/?format=json"
    params = dict(api_key="ozs0jISJX6KiGzDWdXI7h9hCFBwYvk3m11HKkKbe",
                  nutrients=["205", "204", "208", "203"],
                  ndbno=ndbno)

    resp = requests.get(url=search_url, params=params)

    if "No food" in str(resp.json()):
        flash("No foods found.")
        return redirect(url_for('search'))
    else:
        food_name = resp.json()['report']['foods'][0]['name']
        food_measure = resp.json()['report']['foods'][0]['measure']
        food_cals = resp.json()['report']['foods'][0]['nutrients'][0]['value']
        food_protein = resp.json(
        )['report']['foods'][0]['nutrients'][1]['value']
        food_fat = resp.json()['report']['foods'][0]['nutrients'][2]['value']
        food_carbs = resp.json()['report']['foods'][0]['nutrients'][3]['value']

    if request.method == 'GET':
        return render_template(
            'nutrition.html',
            meal=meal,
            date=date,
            food_name=food_name,
            food_measure=food_measure,
            food_cals=food_cals,
            food_protein=food_protein,
            food_fat=food_fat,
            food_carbs=food_carbs,
            ndbno=ndbno,
            form1=form1,
        )

    if request.method == 'POST':
        if meal is None:
            meal_choice = form1.meal.data
        else:
            meal_choice = meal

        try:
            quant_choice = float(form1.quantity.data)
        except:
            flash("Please enter valid values.")
            return redirect(
                url_for('get_nutrition', ndbno=ndbno, meal=meal, date=date))
        else:
            if quant_choice > 10000 or meal_choice not in ("Breakfast",
                                                           "Lunch", "Dinner",
                                                           "Snacks"):
                flash("Please enter valid values.")
                return redirect(
                    url_for('get_nutrition', ndbno=ndbno, meal=meal,
                            date=date))
            else:
                food = Food(food_name=food_name,
                            count=quant_choice,
                            kcal=quant_choice * float(food_cals),
                            protein=quant_choice * float(food_protein),
                            fat=quant_choice * float(food_fat),
                            carbs=quant_choice * float(food_carbs),
                            unit=food_measure,
                            meal=meal_choice,
                            date=date,
                            ndbno=ndbno,
                            user_id=current_user.get_id())
                db.session.add(food)
                db.session.commit()

                return redirect(url_for('diary', date_pick=date))
Ejemplo n.º 24
0
def search(date=None, meal=None):
    form = SearchForm()

    if request.method == 'GET':
        food_list_clean = []
        recent_list = True
        recent_foods = Food.query.filter_by(
            user_id=current_user.get_id()).order_by(desc(Food.id)).group_by(
                Food.food_name)

        for food in recent_foods:
            food_list_clean.append((food.food_name, food.ndbno, food.id))

        return render_template('search.html',
                               form=form,
                               food_list_clean=food_list_clean,
                               recent_list=recent_list,
                               date=date,
                               meal=meal)

    if request.method == 'POST  ':
        if request.form["action"] == "multiadd":
            food_ids = request.form.getlist("selected")

            if meal == None:
                meal = request.form.get('mealselect')

            for food_id in food_ids:
                food = Food.query.filter_by(id=food_id).first()
                food = Food(food_name=food.food_name,
                            count=food.count,
                            kcal=food.kcal,
                            protein=food.protein,
                            fat=food.fat,
                            carbs=food.carbs,
                            unit=food.unit,
                            meal=meal,
                            ndbno=food.ndbno,
                            date=date,
                            user_id=current_user.get_id())
                db.session.add(food)
                db.session.commit()
            return redirect(url_for('diary', date_pick=date))

        else:
            recent_list = False

            # get user input from search bar
            food_search = form.search.data
            if food_search == "":
                return redirect(url_for('search', date=date, meal=meal))

            # build API URL to search for food
            search_url = "https://api.nal.usda.gov/ndb/search/?format=json"
            params = dict(q=food_search,
                          sort="r",
                          max="100",
                          offset="0",
                          ds="Standard Reference",
                          api_key="ozs0jISJX6KiGzDWdXI7h9hCFBwYvk3m11HKkKbe")

            # build list of tuples w/ name of food and associated ndbno (unique ID)
            resp = requests.get(url=search_url, params=params)
            if "zero results" in str(resp.json()):
                flash("No results found.")
                return redirect(url_for('search'))
            else:
                food_list = resp.json()['list']['item']
                food_list_clean = []

                for i in food_list:
                    food_list_clean.append((i['name'], i['ndbno']))

                # return list of food to web page
                return render_template('search.html',
                                       date=date,
                                       meal=meal,
                                       food_list_clean=food_list_clean,
                                       form=form,
                                       recent_list=recent_list)
Ejemplo n.º 25
0
def get_foods():
    page = request.args.get('page', 1, type=int)
    per_page = min(request.args.get('per_page', 10, type=int), 100)
    data = Food.to_collection_dict(Food.query, page, per_page, 'api.get_foods')
    return jsonify(data)
Ejemplo n.º 26
0
def createFood(food_item_info):
    #create tag

    foodName = food_item_info[2].replace('&amp;', '&')
    foodName = convertUni(foodName)

    foodDetail = food_item_info[3].replace('&amp;', '&')
    foodDetail = convertUni(foodDetail)

    foodSource = food_item_info[4].replace('&amp;', '&')
    foodSource = convertUni(foodSource)

    tag = foodName + " " + foodDetail
    tagList = tag.split()
    for i in range(len(tagList)):
        tagList[i] = tagList[i].lower().rstrip(',')
    tagList = list(set(tagList))
    space = " "
    tag = space.join(tagList)
    tag = " " + tag + " "

    #size of this list is 25
    food_item = Food(
        mainType=food_item_info[0],
        type=food_item_info[1],
        food=foodName,
        detail=foodDetail,
        source=foodSource,
        amount=float(convertMixedFraction(str(food_item_info[5]))),
        unit=food_item_info[6],
        gram=float(food_item_info[7]),
        tag=tag
        #nutrients per the stated gram
        ,
        cal_kcal=float(food_item_info[8]),
        calFat_kcal=float(food_item_info[9]),
        fat_g=float(food_item_info[10]),
        fat_pct=float(food_item_info[11]),
        saturFat_g=float(food_item_info[12]),
        polyunFat_g=float(food_item_info[13]),
        monounFat_g=float(food_item_info[14]),
        chol_mg=float(food_item_info[15]),
        sodium_mg=float(food_item_info[16]),
        carb_g=float(food_item_info[17]),
        fiber_g=float(food_item_info[18]),
        sugar_g=float(food_item_info[19]),
        protein_g=float(food_item_info[20]),
        vitA_pct=float(food_item_info[21]),
        vitC_pct=float(food_item_info[22]),
        calcium_pct=float(food_item_info[23]),
        iron_pct=float(food_item_info[24]),
        t0Water_g=float(food_item_info[25]),
        t0Energy_kcal=float(food_item_info[26]),
        t0Energy_kj=float(food_item_info[27]),
        t0Protein_g=float(food_item_info[28]),
        t0TotalLipidFat_g=float(food_item_info[29]),
        t0Carbohydrate_ByDifference_g=float(food_item_info[30]),
        t0Fiber_TotalDietary_g=float(food_item_info[31]),
        t0Sugars_Total_g=float(food_item_info[32]),
        t0Sucrose_g=float(food_item_info[33]),
        t0GlucoseDextrose_g=float(food_item_info[34]),
        t0Fructose_g=float(food_item_info[35]),
        t0Lactose_g=float(food_item_info[36]),
        t0Maltose_g=float(food_item_info[37]),
        t0Galactose_g=float(food_item_info[38]),
        t0Starch_g=float(food_item_info[39]),
        t0AdjustedProtein_g=float(food_item_info[40]),
        t1Calcium_Ca_mg=float(food_item_info[41]),
        t1Iron_Fe_mg=float(food_item_info[42]),
        t1Magnesium_Mg_mg=float(food_item_info[43]),
        t1Phosphorus_P_mg=float(food_item_info[44]),
        t1Potassium_K_mg=float(food_item_info[45]),
        t1Sodium_Na_mg=float(food_item_info[46]),
        t1Zinc_Zn_mg=float(food_item_info[47]),
        t1Copper_Cu_mg=float(food_item_info[48]),
        t1Manganese_Mn_mg=float(food_item_info[49]),
        t1Selenium_Se_mcg=float(food_item_info[50]),
        t1Fluoride_F_mcg=float(food_item_info[51]),
        t2VitaminC_TotalAscorbicAcid_mg=float(food_item_info[52]),
        t2Thiamin_mg=float(food_item_info[53]),
        t2Riboflavin_mg=float(food_item_info[54]),
        t2Niacin_mg=float(food_item_info[55]),
        t2PantothenicAcid_mg=float(food_item_info[56]),
        t2VitaminB_6_mg=float(food_item_info[57]),
        t2Folate_Total_mcg=float(food_item_info[58]),
        t2FolicAcid_mcg=float(food_item_info[59]),
        t2Folate_Food_mcg=float(food_item_info[60]),
        t2Folate_DFE_mcg_DFE=float(food_item_info[61]),
        t2Choline_Total_mg=float(food_item_info[62]),
        t2Betaine_mg=float(food_item_info[63]),
        t2VitaminB_12_mcg=float(food_item_info[64]),
        t2VitaminB_12_Added_mcg=float(food_item_info[65]),
        t2VitaminA_IU_IU=float(food_item_info[66]),
        t2VitaminA_RAE_mcg_RAE=float(food_item_info[67]),
        t2Retinol_mcg=float(food_item_info[68]),
        t2VitaminE_alpha_tocopherol__mg=float(food_item_info[69]),
        t2VitaminE_Added_mg=float(food_item_info[70]),
        t2Tocopherol_Beta_mg=float(food_item_info[71]),
        t2Tocopherol_Gamma_mg=float(food_item_info[72]),
        t2Tocopherol_Delta_mg=float(food_item_info[73]),
        t2VitaminKPhylloquinone_mcg=float(food_item_info[74]),
        t2Carotene_Beta_mcg=float(food_item_info[75]),
        t2Carotene_Alpha_mcg=float(food_item_info[76]),
        t2Cryptoxanthin_Beta_mcg=float(food_item_info[77]),
        t2Lycopene_mcg=float(food_item_info[78]),
        t2Lutein_Zeaxanthin_mcg=float(food_item_info[79]),
        t2VitaminD_IU=float(food_item_info[80]),
        t3Stigmasterol_mg=float(food_item_info[81]),
        t3Phytosterols_mg=float(food_item_info[82]),
        t3Beta_sitosterol_mg=float(food_item_info[83]),
        t3Campesterol_mg=float(food_item_info[84]),
        t3Cholesterol_mg=float(food_item_info[85]),
        t3FattyAcids_TotalMonounsaturated_g=float(food_item_info[86]),
        t3FattyAcids_TotalPolyunsaturated_g=float(food_item_info[87]),
        t3FattyAcids_TotalSaturated_g=float(food_item_info[88]),
        t3FattyAcids_TotalTrans_monoenoic_g=float(food_item_info[89]),
        t3FattyAcids_TotalTrans_polyenoic_g=float(food_item_info[90]),
        t3FattyAcids_TotalTrans_g=float(food_item_info[91]),
        t3MonounsaturatedFats14_1_g=float(food_item_info[92]),
        t3MonounsaturatedFats15_1_g=float(food_item_info[93]),
        t3MonounsaturatedFats16_1C_g=float(food_item_info[94]),
        t3MonounsaturatedFats16_1T_g=float(food_item_info[95]),
        t3MonounsaturatedFats16_1Undifferentiated_g=float(food_item_info[96]),
        t3MonounsaturatedFats17_1_g=float(food_item_info[97]),
        t3MonounsaturatedFats18_1C_g=float(food_item_info[98]),
        t3MonounsaturatedFats18_1T_g=float(food_item_info[99]),
        t3MonounsaturatedFats18_1Undifferentiated_g=float(food_item_info[100]),
        t3MonounsaturatedFats20_1_g=float(food_item_info[101]),
        t3MonounsaturatedFats22_1C_g=float(food_item_info[102]),
        t3MonounsaturatedFats22_1T_g=float(food_item_info[103]),
        t3MonounsaturatedFats22_1Undifferentiated_g=float(food_item_info[104]),
        t3MonounsaturatedFats24_1C_g=float(food_item_info[105]),
        t3PolyunsaturatedFats18_2CLAs_g=float(food_item_info[106]),
        t3PolyunsaturatedFats18_2I_g=float(food_item_info[107]),
        t3PolyunsaturatedFats18_2N_6C_c_g=float(food_item_info[108]),
        t3PolyunsaturatedFats18_2T_t_g=float(food_item_info[109]),
        t3PolyunsaturatedFats18_2TNotFurtherDefined_g=float(
            food_item_info[110]),
        t3PolyunsaturatedFats18_2Undifferentiated_g=float(food_item_info[111]),
        t3PolyunsaturatedFats18_3N_3C_c_c_g=float(food_item_info[112]),
        t3PolyunsaturatedFats18_3N_6C_c_c_g=float(food_item_info[113]),
        t3PolyunsaturatedFats18_3Undifferentiated_g=float(food_item_info[114]),
        t3PolyunsaturatedFats18_3i_g=float(food_item_info[115]),
        t3PolyunsaturatedFats18_4_g=float(food_item_info[116]),
        t3PolyunsaturatedFats20_2N_6C_c_g=float(food_item_info[117]),
        t3PolyunsaturatedFats20_3N_3_g=float(food_item_info[118]),
        t3PolyunsaturatedFats20_3N_6_g=float(food_item_info[119]),
        t3PolyunsaturatedFats20_3Undifferentiated_g=float(food_item_info[120]),
        t3PolyunsaturatedFats20_4N_6_g=float(food_item_info[121]),
        t3PolyunsaturatedFats20_4Undifferentiated_g=float(food_item_info[122]),
        t3PolyunsaturatedFats20_5N_3_g=float(food_item_info[123]),
        t3PolyunsaturatedFats21_5_g=float(food_item_info[124]),
        t3PolyunsaturatedFats22_4_g=float(food_item_info[125]),
        t3PolyunsaturatedFats22_5N_3_g=float(food_item_info[126]),
        t3PolyunsaturatedFats22_6N_3_g=float(food_item_info[127]),
        t3SaturatedFats10_0_g=float(food_item_info[128]),
        t3SaturatedFats12_0_g=float(food_item_info[129]),
        t3SaturatedFats13_0_g=float(food_item_info[130]),
        t3SaturatedFats14_0_g=float(food_item_info[131]),
        t3SaturatedFats15_0_g=float(food_item_info[132]),
        t3SaturatedFats16_0_g=float(food_item_info[133]),
        t3SaturatedFats17_0_g=float(food_item_info[134]),
        t3SaturatedFats18_0_g=float(food_item_info[135]),
        t3SaturatedFats20_0_g=float(food_item_info[136]),
        t3SaturatedFats22_0_g=float(food_item_info[137]),
        t3SaturatedFats24_0_g=float(food_item_info[138]),
        t3SaturatedFats4_0_g=float(food_item_info[139]),
        t3SaturatedFats6_0_g=float(food_item_info[140]),
        t3SaturatedFats8_0_g=float(food_item_info[141]),
        t4Alanine_g=float(food_item_info[142]),
        t4Arginine_g=float(food_item_info[143]),
        t4AsparticAcid_g=float(food_item_info[144]),
        t4Cystine_g=float(food_item_info[145]),
        t4GlutamicAcid_g=float(food_item_info[146]),
        t4Glycine_g=float(food_item_info[147]),
        t4Histidine_g=float(food_item_info[148]),
        t4Hydroxyproline_g=float(food_item_info[149]),
        t4Isoleucine_g=float(food_item_info[150]),
        t4Leucine_g=float(food_item_info[151]),
        t4Lysine_g=float(food_item_info[152]),
        t4Methionine_g=float(food_item_info[153]),
        t4Phenylalanine_g=float(food_item_info[154]),
        t4Proline_g=float(food_item_info[155]),
        t4Serine_g=float(food_item_info[156]),
        t4Threonine_g=float(food_item_info[157]),
        t4Tryptophan_g=float(food_item_info[158]),
        t4Tyrosine_g=float(food_item_info[159]),
        t4Valine_g=float(food_item_info[160]),
        t5Ash_g=float(food_item_info[161]),
        t5Alcohol_Ethyl_g=float(food_item_info[162]),
        t5Caffeine_mg=float(food_item_info[163]),
        t5Theobromine_mg=float(food_item_info[164]))

    return food_item
Ejemplo n.º 27
0
def run():
    """Import data from companies.json and people.json"""
    app = create_app(os.getenv('FLASK_CONFIG') or 'default')

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

        # Process companies.json
        companies_to_add = []

        with open('resources/companies.json', 'r') as f:
            companies = json.load(f)
            for item in companies:
                company = Company(index=item['index'], name=item['company'])
                companies_to_add.append(company)

        db.session.add_all(companies_to_add)

        # Process people.json
        people_to_add = []
        with open('resources/people.json', 'r') as f:
            people = json.load(f)
            for item in people:
                print('Processing {}'.format(item['index']))
                # Import a person
                person = Person(index=item['index'],
                                name=item['name'],
                                has_died=item['has_died'],
                                age=item['age'],
                                eye_color=item['eyeColor'],
                                phone=item['phone'],
                                address=item['address'],
                                )

                # Assign company to person
                company = Company.query.filter_by(index=item['company_id']).first()
                if not company:
                    # If we don't have a company with this index, this person cannot be imported.
                    print('Company not found index {} for person index {} {}. Skip this item'.format(item['company_id'],
                                                                                                     item['index'],
                                                                                                     item['name']))
                    continue

                person.company = company

                # Assign food to person, also record new food item as we go
                for food_item in item['favouriteFood']:
                    food = Food.query.filter_by(name=food_item).first()
                    if not food:
                        food = Food(name=food_item, type=determine_food_type(food_item))
                    person.foods.append(food)

            # Process friendship
            for item in people:
                print('Processing {}'.format(item['index']))
                person = Person.query.filter_by(index=item['index']).first()
                if not person:
                    continue

                for friend_item in item['friends']:
                    friend = Person.query.filter_by(index=friend_item['index']).first()
                    if not friend:
                        continue
                    if person.index == friend.index:
                        continue

                    print('{} befriends {}'.format(person.index, friend.index))
                    person.befriend(friend)

                people_to_add.append(person)

        db.session.add_all(people_to_add)

        # Finalise changes to database
        db.session.commit()
Ejemplo n.º 28
0
def add_post():
    post_data = json.loads(request.get_data())
    if 'title' not in post_data:
        return bad_request("A post title is required.")
    else:
        if 'muscle_group' in post_data:
            post = Post(post_data)
            db.session.add(post)
            db.session.commit()
            exercise = Exercise(post_data, post.id)
            db.session.add(exercise)
            db.session.commit()
            response = {
                'post': {
                    'id': post.id,
                    'title': post.title,
                    'description': post.description,
                    'image_url': post.image_url,
                    'user_id': post.user_id,
                    'date': post.date,
                    'post_type': 'exercise',
                    'exercise': {
                        'id': exercise.id,
                        'muscle_group': exercise.muscle_group,
                        'name': exercise.name,
                        'reps': exercise.reps,
                        'weight': exercise.weight,
                        'time': exercise.time,
                        'distance': exercise.distance
                    }
                }
            }
            return jsonify(response)
        elif 'meal' in post_data:
            post = Post(post_data)
            db.session.add(post)
            db.session.commit()
            meal = Meal(post_data, post.id)
            db.session.add(meal)
            db.session.commit()
            foods = post_data['meal']['foods']
            food_obs = []
            for i, x in enumerate(foods, start=0):
                food = Food(foods[i])
                food_obs.append(food)
                db.session.add(food)
                db.session.commit()
                meal.foods.append(food)
                db.session.commit()
            response = {
                'post': {
                    'id': post.id,
                    'title': post.title,
                    'description': post.description,
                    'image_url': post.image_url,
                    'user_id': post.user_id,
                    'date': post.date,
                    'post_type': 'meal',
                    'meal': {
                        'id': meal.id,
                        'name': meal.name,
                        'post_id': meal.post_id,
                        'foods': get_foods(food_obs)
                    }
                }
            }

            return jsonify(response)
        else:
            return bad_request("AHHH! Something went wrong!")
Ejemplo n.º 29
0
    def test_put_food(self):
        u = push_dummy_user()
        push_dummy_list(u, 'TestyList')
        with self.test_client:
            self.login(u.username)

            list_ = List.query.first()
            food = Food(list_id=list_.id, name='Food')
            db.session.add(food)
            db.session.commit()

            foodcat = FoodCategory(list_id=list_.id, name='Cat')
            db.session.add(foodcat)
            db.session.commit()
            foodcatass = FoodCategoryAssociation(
                food_id=food.id, category_id=foodcat.id)
            db.session.add(foodcatass)
            db.session.commit()

            foodcat = FoodCategory(list_id=list_.id, name='Cat_Remove')
            db.session.add(foodcat)
            db.session.commit()
            foodcatass = FoodCategoryAssociation(
                food_id=food.id, category_id=foodcat.id)
            db.session.add(foodcatass)
            db.session.commit()

            foodcat = FoodCategory(list_id=list_.id, name='Cat_Add')
            db.session.add(foodcat)
            db.session.commit()

            rsp = self.test_client.get('/api/lists/1/foods')
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [{
                'id': 1,
                'name': 'Food',
                'categories': [1, 2]
            }])

            rsp = self.test_client.put('/api/lists/1/foods/1', json=dict(
                name='UpdatedFood',
                categories=[
                    'Cat',
                    'NewCat',
                    'Cat_Add'
                ]
            ))
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [{
                'id': 1,
                'name': 'UpdatedFood',
                'categories': [1, 4, 3]
            }])

            rsp = self.test_client.put('/api/lists/1/foods/1', json=dict(
                name='UpdatedFood',
                categories=[
                    'Cat',
                    'NewCat',
                    'NewestCat'
                ]
            ))
            data = rsp.get_json()
            self.assertEqual(rsp.status, '200 OK')
            self.assertEqual(data, [{
                'id': 1,
                'name': 'UpdatedFood',
                'categories': [1, 4, 5]
            }])

            rsp = self.test_client.put('/api/lists/1/foods/1', json=dict(
                name='UpdatedFood'
            ))
            self.assertEqual(rsp.status, '400 BAD REQUEST')

            rsp = self.test_client.put('/api/lists/1/foods/1', json=dict(
                categories=['UpdatedFood']
            ))
            self.assertEqual(rsp.status, '400 BAD REQUEST')

            rsp = self.test_client.put('/api/lists/1/foods/1', data=dict(
                name='UpdatedFood',
                categories=[
                    'Cat',
                    'NewCat'
                ]
            ))
            self.assertEqual(rsp.status, '400 BAD REQUEST')

            rsp = self.test_client.put('/api/lists/1/foods/5', json=dict(
                name='UpdatedFood',
                categories=[
                    'Cat',
                    'NewCat'
                ]
            ))
            self.assertEqual(rsp.status, '404 NOT FOUND')