예제 #1
0
def load_ingredients():
    """Load ingrdients into database."""

    print("Ingredients")

    for i, row in enumerate(open("seed_data/ingredients.seed.txt")):
        row = row.rstrip()

        user_id, ingredient_id, ingredient_name, quantity, units = row.split("|")[:5]

        
        ingredient = Ingredient(ingredient_id=ingrdient_id,
                      ingredient_name=ingredient_name,
                      quantity=quantity,
                      units=units)

        # We need to add to the session or it won't ever be stored
        db.session.add(ingredient)

        # provide some sense of progress
        if i % 100 == 0:
            print(i)

    # Once we're done, we should commit our work
    db.session.commit()
예제 #2
0
def create_ingredient(ingredient_name, type_id):  # -- TESTED
    """Create new ingredient in db."""

    new_ingredient = Ingredient(ingredient_name=ingredient_name,
                                type_id=type_id)
    db.session.add(new_ingredient)
    db.session.commit()
예제 #3
0
def add_ingredient(user_id, ingredient):
    """Add ingredident to user's inventory if not already existing"""

    user = User.query.filter(User.user_id == user_id).one()
    #Check if ingredient is in master list and then if it is in user's inventory
    if Ingredient.query.filter(Ingredient.ingred_name == ingredient).all():
        ingredient_id = Ingredient.query.filter(
            Ingredient.ingred_name == ingredient).one().ingred_id
        if UserIngredient.query.filter(
                UserIngredient.user_id == user_id,
                UserIngredient.ingred_id == ingredient_id).all():
            return jsonify({})
        else:
            new_user_ingred = UserIngredient(ingred_id=ingredient_id,
                                             user_id=user.user_id)
            db.session.add(new_user_ingred)
            db.session.commit()
            ingred_id = str(new_user_ingred.ingred_id)
            print ingred_id
            return jsonify({'ingredient': ingredient, 'ingred_id': ingred_id})

    #If ingredient not in master ingredient list, add to master ingredients
    #and also add to user's ingredient inventory
    else:
        new_ingred = Ingredient(ingred_name=ingredient)
        db.session.add(new_ingred)
        db.session.flush()
        new_user_ingred = UserIngredient(ingred_id=new_ingred.ingred_id,
                                         user_id=user.user_id)
        db.session.add(new_user_ingred)
        db.session.commit()
        ingred_id = str(new_ingred.ingred_id)
        print ingred_id

        return jsonify({'ingredient': ingredient, 'ingred_id': ingred_id})
예제 #4
0
def add_ingredient(name, location):
    """add ingredient"""
    ingredient = Ingredient(name=name, location=location)
    db.session.add(ingredient)
    db.session.commit()

    return ingredient
예제 #5
0
def load_ingredients(qty_data):
    """ Load ingredients into INGREDIENT_ATTRIBUTES table """

    print "Adding Ingredients"

    # Delete all rows in table, so sample table can be created repeatedly with
    # new data and no duplicates
    # Ingredient.query.delete()

    for item in qty_data:
        if len(item) == 0:
            pass
        else:
            ingredient_name = item
            whole_grams = 100
            calories_per_whole = None
            carbs_per_whole = None
            sugar_per_whole = None

            ingredient = Ingredient(ingredient_name=ingredient_name,
                                    whole_grams=whole_grams,
                                    calories_per_whole=calories_per_whole,
                                    carbs_per_whole=carbs_per_whole,
                                    sugar_per_whole=sugar_per_whole)

            db.session.add(ingredient)

    db.session.commit()
예제 #6
0
def load_ingredients(ingredients_per_recipe):
    """ Load ingredients into INGREDIENT_ATTRIBUTES table """

    print "Adding Ingredient"

    # Delete all rows in table, so sample table can be created repeatedly with
    # new data and no duplicates
    SampleFNRecipe.query.delete()

    for value in ingredients_per_recipe:
        for item in value:
            ingredient_name = item
            whole_grams = 100
            calories_per_whole = None
            carbs_per_whole = None
            sugar_per_whole = None

            ingredient = Ingredient(ingredient_name=ingredient_name,
                                    whole_grams=whole_grams,
                                    calories_per_whole=calories_per_whole,
                                    carbs_per_whole=carbs_per_whole,
                                    sugar_per_whole=sugar_per_whole)

            db.session.add(ingredient)
            print "Ingredient Added"

    db.session.commit()
예제 #7
0
def create_ingredient(ingredient_name):
    """Create, add to db, and return an ingredient."""

    ingredient = Ingredient(ingredient_name=ingredient_name)

    db.session.add(ingredient)
    db.session.commit()

    return ingredient
예제 #8
0
def seed_data(str_data):
    """Seed all ingredients into database"""

    str_data = str_data.split('\n')
    for ingredient in str_data:

        new_ingredient = Ingredient(ing_name=ingredient)
        db.session.add(new_ingredient)

        db.session.commit()
예제 #9
0
def add_missing_ingredients():
    """ Displays shopping list with missing ingredients."""

    new_recipes_to_add = db.session.query(UserRecipe.recipe_id).filter(
        UserRecipe.user_id == session['user_id'],
        UserRecipe.status == 'needs_missing_ingredients').all()

    new_recipe_list = []
    for recipe in new_recipes_to_add:
        new_recipe_list.append(recipe[0])

    new_shopping_list = ShoppingList(
        user_id=session['user_id'],
        has_shopped=False,
    )
    db.session.add(new_shopping_list)

    current_user = User.query.get(session['user_id'])

    results_recipes = current_user.get_used_and_missing_ingredients(
        new_recipe_list)

    for recipe in results_recipes:
        for missing_ingredient in results_recipes[recipe]['missing_ing']:
            ingredient = Ingredient.query.filter(
                Ingredient.ingredient_id == missing_ingredient[0]).first()
            if not ingredient:
                new_missing_ingredient = Ingredient(
                    ingredient_id=missing_ingredient[0],
                    ingredient_name=missing_ingredient[3],
                    base_unit=missing_ingredient[2],
                    ingredient_aisle=missing_ingredient[4],
                )
                db.session.add(new_missing_ingredient)

            new_list_ingredient = ListIngredient(
                shopping_list_id=new_shopping_list.list_id,
                ingredient_id=missing_ingredient[0],
                aggregate_quantity=missing_ingredient[1],
            )

            db.session.add(new_list_ingredient)

    # Update status of recipes added to shopping list to 'in progress'
    update_recipes = UserRecipe.query.filter(
        UserRecipe.user_id == session['user_id'],
        UserRecipe.status == 'needs_missing_ingredients').all()
    for recipe in update_recipes:
        recipe.status = 'in_progress'
        db.session.commit()

    user_ingredients = new_shopping_list.get_ingredients()

    return render_template("shopping.html", ingredients=user_ingredients)
예제 #10
0
def create_ingredient(name, calories, measurement, photo):
    """Creates an ingredient"""

    ingredient = Ingredient(name=name,
                            calories=calories,
                            measurement=measurement,
                            photo=photo)

    db.session.add(ingredient)
    db.session.commit()

    return ingredient
예제 #11
0
def load_ingredients():
    """Load ingredients from spoonacular_api_1000.info into ingredients table in database."""
    # Delete rows in ingredients table when we run this file so we won't have duplicates.
    Ingredient.query.delete()

    for row in open("seed_data/spoonacular_api_1000.info"):
        row = row.rstrip()
        ingredient, api_id = row.split(";")

        # Instantiate Ingredient object with information from each row.
        new_ing = Ingredient(name=ingredient, api_id=api_id)
        db.session.add(new_ing)

    db.session.commit()
예제 #12
0
def create_ingredient(ingredient_name):
    """Create and return a new ingredient."""

    # Check if ingredient already exists
    ingredient = Ingredient.query.filter(
        Ingredient.ingredient_name == ingredient_name).first()

    # If ingredient does not already exists, create it and add to database
    if not ingredient:
        ingredient = Ingredient(ingredient_name=ingredient_name.title())

        db.session.add(ingredient)
        db.session.commit()

    return ingredient
예제 #13
0
def show_shopping_list():
    """ Creates shopping list of missing ingredients with aggregated quantities and base units."""

    all_user_recipes = db.session.query(UserRecipe.recipe_id).filter(
        UserRecipe.user_id == session['user_id'],
        UserRecipe.status == 'needs_ingredients').all()
    new_shopping_list = ShoppingList(
        user_id=session['user_id'],
        has_shopped=False,
    )
    db.session.add(new_shopping_list)

    aggregated_ingredients = aggregate_ingredients(all_user_recipes)

    for ingredient_id in aggregated_ingredients:
        ingredient = db.session.query(Ingredient).filter(
            Ingredient.ingredient_id == ingredient_id).first()

        if not ingredient:
            new_ingredient = Ingredient(
                ingredient_id=ingredient_id,
                ingredient_name=aggregated_ingredients[ingredient_id]['name'],
                base_unit=aggregated_ingredients[ingredient_id]['unit'],
                ingredient_aisle=aggregated_ingredients[ingredient_id]
                ['aisle'],
            )
            db.session.add(new_ingredient)

        new_list_ingredient = ListIngredient(
            shopping_list_id=new_shopping_list.list_id,
            ingredient_id=ingredient_id,
            aggregate_quantity=aggregated_ingredients[ingredient_id]
            ['quantity'],
        )
        db.session.add(new_list_ingredient)

    # Update status of recipes added to shopping list to 'in progress'
    update_recipes = UserRecipe.query.filter(
        UserRecipe.user_id == session['user_id'],
        UserRecipe.status == 'needs_ingredients').all()
    for recipe in update_recipes:
        recipe.status = 'in_progress'

    db.session.commit()

    user_ingredients = new_shopping_list.get_ingredients()

    return render_template("shopping.html", ingredients=user_ingredients)
예제 #14
0
def load_ingredients():
    """Load all categories."""

    ingredients_file = open("./seed_data/ingr_info.tsv")

    for row in ingredients_file:
        ingredient_info = row.strip().split("\t")

        ingredient_id, name = int(ingredient_info[0]), ingredient_info[1]  

        print (ingredient_id)
        print (name) 

        ingredient = Ingredient(id=ingredient_id, name=name)
        db.session.add(ingredient)
    
    db.session.commit()   
예제 #15
0
def load_ingredients(all_ingredients):
    """Load ingredients for the recipe."""

    print "Ingredient(s)"

    for ingredient in all_ingredients:
        ingredient_name = ingredient['name']
        type_name = ingredient['aisle']

        if not Ingredient.query.filter_by(
                ingredient_name=ingredient_name).all():
            type_id = IngredientType.query.filter_by(
                type_name=type_name).first().type_id
            ingredient = Ingredient(ingredient_name=ingredient_name,
                                    type_id=type_id)

            db.session.add(ingredient)

    db.session.commit()
예제 #16
0
def ingredients():
    # Query the ingredients data
    ingredients = db2.query(Ingredient).all()
    # Generate form to add ingredients
    form = IngredientForm(request.form)

    if form.validate_on_submit():
        new_ingredient = Ingredient(name=form.ingredient.data.strip().lower())
        new_ingredient.type = db2.query(Type).filter(
            Type.type == form.type.data).one()
        db2.add(new_ingredient)
        db2.commit()
        flash(('Successfully added ' + form.ingredient.data.strip().lower()),
              "success")
        return redirect(url_for('ingredients'))

    return render_template("ingredients.html",
                           ingredients=ingredients,
                           form=form)
예제 #17
0
def load_ingredients():
    """Loads ingredient data"""

    prod_ing_dict = create_product_ingredient_dictionary()
    ingredient_list = []

    for key, value in prod_ing_dict.items():
        for ingredient in value:
            ingredient_list.append(ingredient)

    # making list of unique ingredients
    ingredient_list = list(set(ingredient_list))

    for ingredient in ingredient_list:
        # creating ingredient instance
        ingredient = Ingredient(ing_name=ingredient)

        db.session.add(ingredient)

    db.session.commit()
예제 #18
0
def add_new_ingredient(ingredient_name,
                       dairy_free=True,
                       gluten_free=True,
                       vegetarian=True,
                       vegan=True,
                       paleo=True):
    """Add new ingredient to db"""
    current_ingredient = Ingredient(ingredient_name=ingredient_name.lower(),
                                    dairy_free=dairy_free,
                                    gluten_free=gluten_free,
                                    vegetarian=vegetarian,
                                    vegan=vegan,
                                    paleo=paleo)

    # float the metric amount

    db.session.add(current_ingredient)
    db.session.commit()

    return current_ingredient
예제 #19
0
def add_ingredients(recipe_id, ingredients_info):
    """Adds recipe's ingredients to Ingredient table in DB. This in turn
    also requires adding ingredient's aisles to Aisle table and populating
    RecipeIngredient table."""

    # Loop through ing. list, adding new ingredients and aisles to DB if necessary
    for ingredient_info in ingredients_info:
        ingredient_id = str(ingredient_info['id'])
        ingredient_exists = check_if_ingredient_exists(ingredient_id)

        if not ingredient_exists:
            # create Ingredient object that may or may not have aisle id info
            new_ingredient = Ingredient(ing_id=ingredient_id,
                                        ing_name=ingredient_info['name'])

            aisle_name = ingredient_info['aisle']
            aisle_exists = check_if_aisle_exists(aisle_name)

            if not aisle_exists:
                new_aisle = add_aisle(aisle_name)
                new_ingredient.aisle_id = new_aisle.aisle_id
            else:
                new_ingredient.aisle_id = aisle_exists.aisle_id

            # At this point, new_ingredient should have an aisle_id
            # Add completed new_ingredient to DB
            db.session.add(new_ingredient)
            db.session.commit()

            # Add new ing to RecipeIngredient table
            add_recipe_ingredient(recipe_id, ingredient_id,
                                  ingredient_info['unit'],
                                  ingredient_info['amount'])
        else:
            # Add already-existing ing to RecipeIngredient table, since this is
            # always going to be a new recipe (indicated in server.py conditional).
            # This ing could already exist in DB due to past recipes using the
            # same ingredient.
            add_recipe_ingredient(recipe_id, ingredient_id,
                                  ingredient_info['unit'],
                                  ingredient_info['amount'])
예제 #20
0
def add_items():
    """Add ingredients to items table in database. If ingredient isn't already in ingredients table, also add to ingredients table."""
    # Get items saved in "ingredients" from my_items.html in list form
    items = request.form.getlist("ingredients")
    items_json = []

    # Loop over each item user selected
    for item in items:
        # Check if item exists in ingredients table
        if item.isdigit() and Ingredient.query.get(item) != None:
            # Create Item instance to add to items table if it's not in the user's kitchen yet
            if Item.query.filter_by(user_id=session["user_id"],
                                    ing_id=int(item)).first() == None:
                items_json.append(create_item(int(item)))

        # If item isn't an int, it is something the user wrote in:
        else:
            # Create new Ingredient
            new_ing = Ingredient(name=item.lower())
            db.session.add(new_ing)
            db.session.commit()
            items_json.append(create_item(new_ing.ing_id))

    return jsonify(items_json)
예제 #21
0
def load_recipe_ingredients(recipe_name, all_ingredients, scrape_ingredients):
    """Load recipeingredients into database."""

    print "Recipe Ingredients"

    recipe_id = Recipe.query.filter_by(
        recipe_name=recipe_name).first().recipe_id

    for i in range(len(scrape_ingredients)):
        original_string = scrape_ingredients[i]['stripped_ingredient']
        ingredient_id = None
        ingredient_ids = []
        for ingredient in all_ingredients:
            name = ingredient['name']
            name_words = name.split()

            # to make sure the original string from webscrape
            # matches the correct ingredient name received from the api
            if len(name_words) > 1:
                if name_words[-1] in original_string and name_words[
                        -2] in original_string:
                    ingredient_id = Ingredient.query.filter_by(
                        ingredient_name=name).first().ingredient_id
                    ingredient_ids.append(ingredient_id)
            elif len(name_words) == 1:
                if name in original_string:
                    ingredient_id = Ingredient.query.filter_by(
                        ingredient_name=name).first().ingredient_id
                    ingredient_ids.append(ingredient_id)

        new_ingredient = None
        if not ingredient_ids:
            new_string = original_string
            if re.search(r'\(.*\)', new_string):
                new_string = ''.join(
                    filter(None, re.split(r'\(.*\)', new_string)))
            if re.search(r'[A-Za-z]+ed', new_string):
                new_string = ''.join(
                    filter(None, re.split(r'[A-Za-z]+ed', new_string)))
            if re.search(r'\,.*', new_string):
                new_string = ''.join(
                    filter(None, re.split(r'\,.*', new_string)))
            new_string = new_string.split()
            for i in range(len(new_string)):
                new_string[i] = new_string[i].strip()
            new_string = ' '.join(new_string)
            if not Ingredient.query.filter_by(
                    ingredient_name=new_string).all():
                new_ingredient = Ingredient(ingredient_name=new_string)
                db.session.add(new_ingredient)

        if not ingredient_id:
            ingredient_id = Ingredient.query.filter_by(
                ingredient_name=new_string).first().ingredient_id
        # to make sure the same ingredient is not added to the same
        # recipe multiple times
        if not RecipeIngredient.query.filter_by(
                original_string=original_string).all():
            if scrape_ingredients[i].get('link'):
                link = scrape_ingredients[i]['link']
                recipeingredient = RecipeIngredient(
                    original_string=original_string,
                    recipe_id=recipe_id,
                    ingredient_id=ingredient_id,
                    link=link)
            else:
                recipeingredient = RecipeIngredient(
                    original_string=original_string,
                    recipe_id=recipe_id,
                    ingredient_id=ingredient_id)
            db.session.add(recipeingredient)

    db.session.commit()
예제 #22
0
def get_recipe_attributes_db(name, p):
	"""Get the recipes' attributes."""


	payload = { 'q': name,
				'app_id': EDAMAM_RECIPE_SEARCH_APPLICATION_ID,
				'app_key': EDAMAM_RECIPE_SEARCH_APPLICATION_KEY }
	
	response = requests.get(EDAMAM_URL, params=payload)
	data = response.json()


	if response.ok:
		for n in range(p):
			recipe_obj = Recipe(recipe_name=data["hits"][n]["recipe"]["label"],
								recipe_url=data["hits"][n]["recipe"]["uri"],
								recipe_image=data["hits"][n]["recipe"]["image"],
								directions=data["hits"][n]["recipe"]["url"],
								servings=data["hits"][n]["recipe"]["yield"],
								calories=data["hits"][n]["recipe"]["calories"],
								carbohydrates=data["hits"][n]["recipe"]["totalNutrients"]["CHOCDF"]["quantity"],
								fat=data["hits"][n]["recipe"]["totalNutrients"]["FAT"]["quantity"],
								protein=data["hits"][n]["recipe"]["totalNutrients"]["PROCNT"]["quantity"])
			db.session.add(recipe_obj)
			db.session.commit()


			recipe_labels_1 = data["hits"][n]["recipe"]["dietLabels"]
			recipe_labels = data["hits"][n]["recipe"]["healthLabels"]

			for rec_lab_1 in recipe_labels_1:
				recipe_labels.append(rec_lab_1)

			diet_id_lst = []
			for recipe_label in recipe_labels:
				label = Diet.query.filter_by(diet_name=recipe_label).first()
				diet_id = label.diet_id
				diet_id_lst.append(diet_id)



			for diet_id in diet_id_lst:
				diet_connection = RecipeDiet(recipe_id=recipe_obj.recipe_id, diet_id=diet_id)
				db.session.add(diet_connection)

			recipe_cautions = data["hits"][n]["recipe"]["cautions"]

			cautions_id_lst = []

			for caution in recipe_cautions:

				caution_obj = Allergy.query.filter_by(allergy_name=caution).first()

				caution_id = caution_obj.allergy_id
				cautions_id_lst.append(caution_id)




			for caution_id in cautions_id_lst:
				caution_connection = RecipeAllergy(recipe_id=recipe_obj.recipe_id, allergy_id=caution_id)
				db.session.add(caution_connection)




			ingredients = data["hits"][n]["recipe"]["ingredientLines"]
			
			for i, ingredient in enumerate(ingredients):
				ingredient_obj = Ingredient(ingredient_name=ingredient)
				db.session.add(ingredient_obj)
				db.session.commit()
				recipe_ingredient_obj = RecipeIngredient(ingredient_id=ingredient_obj.ingredient_id, 
														recipe_id=recipe_obj.recipe_id, 
														amount=data["hits"][n]["recipe"]["ingredients"][i]["weight"])
				db.session.add(recipe_ingredient_obj)	
			print (recipe_cautions)

		db.session.commit()
예제 #23
0
with open(file_ingredients, 'r') as file:
    reader = csv.DictReader(file)

    # Insert records into Type
    types = reader.fieldnames[1:]
    types_dict = {}
    for item in types:
        types_dict[item] = Type(type=item)
        db.add(types_dict[item])
    db.commit()

    # Insert records into Ingredient
    for row in reader:
        for type in types:
            if row[type] == "TRUE":
                ingredient = Ingredient(name=row['name'])
                ingredient.type = types_dict[type]
                db.add(ingredient)
                db.commit()

with open(file_methods, 'r') as file:
    reader = list(csv.DictReader(file))

    # Insert records into Style
    styles = set()
    for row in reader:
        styles.add(row['style'])
    styles_dict = {}
    for item in styles:
        styles_dict[item] = Style(style=item)
        db.add(styles_dict[item])
예제 #24
0
def add_new_recipe(user_id, recipe_id):
    """Add recipe to user's recipe box"""
    user = User.query.filter(User.user_id == user_id).one()
    saved_recipe = get_recipe_info(recipe_id)
    saved_recipe_title = saved_recipe['title'].encode('utf-8')
    saved_recipe_source_name = saved_recipe.get('sourceName')
    saved_recipe_source_url = saved_recipe.get('sourceUrl')
    saved_recipe_image_url = saved_recipe.get('image')
    print saved_recipe_image_url

    steps = saved_recipe['analyzedInstructions'][0]['steps']
    step_instructions = []  #create list for all instruction steps

    for step in steps:
        if len(step['step']) > 1:
            step_instructions.append(step['step'])

    if not Recipe.query.filter(Recipe.url == saved_recipe_source_url).all():
        #Create new recipe for database if does not exist already
        new_recipe = Recipe(title=saved_recipe_title,
                            source_name=saved_recipe_source_name,
                            url=saved_recipe_source_url,
                            instructions=step_instructions,
                            image=saved_recipe_image_url)

        db.session.add(new_recipe)
        db.session.flush()

        new_recipe_id = new_recipe.recipe_id

        ingredients = saved_recipe[
            'extendedIngredients']  # list of dictionaries. each dict contains info about all ingredients, including 'name', 'amount', 'unit'
        #Create Ingredient instances for ingredients that do not already exist in db
        for ingredient in ingredients:
            ingredient_name = ingredient['name']
            ingredient_amt = round(ingredient['amount'], 2)
            ingredient_unit = ingredient['unitShort']
            if not Ingredient.query.filter(
                    Ingredient.ingred_name == ingredient_name).all(
                    ):  #if ingredient not in db. add to it
                new_ingred = Ingredient(ingred_name=ingredient_name)
                db.session.add(new_ingred)
                db.session.flush()

            ingred_id = Ingredient.query.filter(
                Ingredient.ingred_name == ingredient_name).one().ingred_id

            #Create RecipeIngredient instances
            ingred_info = str(ingredient_amt) + " " + ingredient_unit.lower(
            ) + " - " + ingredient_name.title()

            new_recipe_ingred = RecipeIngredient(recipe_id=new_recipe_id,
                                                 ingred_id=ingred_id,
                                                 ingred_info=ingred_info)
            db.session.add(new_recipe_ingred)
            db.session.flush()

    existing_recipe_id = Recipe.query.filter(
        Recipe.url == saved_recipe_source_url).one().recipe_id

    if not UserRecipe.query.filter(UserRecipe.user_id == user_id,
                                   UserRecipe.recipe_id
                                   == existing_recipe_id).all():
        new_user_recipe = UserRecipe(recipe_id=existing_recipe_id,
                                     user_id=user_id,
                                     cooked=False)
        db.session.add(new_user_recipe)
        db.session.flush()

    db.session.commit()

    return jsonify({})
예제 #25
0
def get_recipe():
    """ Gets users food choice(s) and nutrient choice(s) from browser, and calls Edamam API to search for a food choice 
	meeting nutrition criteria specified by the user """

    food_choice = request.args.get("food")

    list_of_selected_nutrients = request.args.getlist("nutrient")

    nutrient_parameters = get_nutrient_search_parameters(
        list_of_selected_nutrients)

    api_url = 'https://api.edamam.com/search?q=' + food_choice + '&app_id=701b2057&app_key=9f957ee3872be9ddfbadfd3ee005f3a2'

    api_url += nutrient_parameters

    r = requests.get(api_url)

    recipes_json = r.json()

    list_of_recipes = []

    # all recipes in response are contained within 'hits'. All other information is not needed.
    parsed_recipes = recipes_json['hits']

    # Iterates through API, which is a list of dictionaries. Parses recipes
    for parsed_recipe in parsed_recipes:

        # "recipe" is a key which has a corresponding value of a dictionary holding recipe_name, recipe_image,
        # recipe_blog_url, recipe_yield, recipe_ingredient_list, and recipe_labels. "totalNutrients" is a key
        # within that dictionary which has a corresponding value of a dictionary holding nutrients.
        # However, since some nutrient keys are mssing, .get is used.
        recipe = parsed_recipe["recipe"]
        recipe_nutrient = recipe["totalNutrients"]

        recipe_name = recipe.get("label", "no name available")
        recipe_image = recipe.get("image", "no image available")
        recipe_url = recipe.get("url", "no url available")
        recipe_blog_url = recipe.get("shareAs")
        recipe_yield = recipe.get("yield", 0)
        recipe_ingredients_list = recipe.get("ingredientLines",
                                             "No Ingredients Available")

        recipe_diet_labels = recipe["dietLabels"]
        recipe_health_labels = recipe["healthLabels"]
        recipe_caution_labels = recipe["cautions"]

        # Lines 186-196:
        # In API response, nutrient is a key, and value is a dictionary which contains string "quantity"
        # as a key, and value is an integer of quantity of nutrient. See below:
        #  "K" : {
        #   "label" : "Potassium",
        #   "quantity" : 7402.711141533334,
        #   "unit" : "mg"
        # },
        # in case a nutrient key is missing, will assume value of nutrient is 0.
        # If nutrinet is missing, will set default value to an empty dictionary.
        # By defaily, string "quantity" will not found in empty dictionary and 0 is returned.
        recipe_nutrient_calories = recipe_nutrient.get("ENERC_KCAL", {})
        recipe_nutrient_carbohydrates = recipe_nutrient.get("CHOCDF", {})
        recipe_nutrient_protein = recipe_nutrient.get("PROCNT", {})
        recipe_nutrient_fiber = recipe_nutrient.get("FIBTG", {})
        recipe_nutrient_fat = recipe_nutrient.get("FAT", {})
        recipe_nutrient_potassium = recipe_nutrient.get("K", {})
        recipe_nutrient_phosphorus = recipe_nutrient.get("P", {})
        recipe_nutrient_sodium = recipe_nutrient.get("NA", {})
        recipe_nutrient_saturated_fat = recipe_nutrient.get("FASAT", {})
        recipe_nutrient_iron = recipe_nutrient.get("FE", {})

        recipe_calories = recipe_nutrient_calories.get("quantity", 0)
        recipe_carbohydrates = recipe_nutrient_carbohydrates.get("quantity", 0)
        recipe_protein = recipe_nutrient_protein.get("quantity", 0)
        recipe_fiber = recipe_nutrient_fiber.get("quantity", 0)
        recipe_fat = recipe_nutrient_fat.get("quantity", 0)
        recipe_potassium = recipe_nutrient_potassium.get("quantity", 0)
        recipe_phosphorus = recipe_nutrient_phosphorus.get("quantity", 0)
        recipe_sodium = recipe_nutrient_sodium.get("quantity", 0)
        recipe_saturated_fat = recipe_nutrient_saturated_fat.get("quantity", 0)
        recipe_iron = recipe_nutrient_iron.get("quantity", 0)

        # API separates three different types of labels, but this app will combine them together
        labels = recipe_diet_labels + recipe_health_labels + recipe_caution_labels

        # making a dictionary of necessary pieces of recipe
        recipe_components = {
            'recipe_name': recipe_name,
            'recipe_image': recipe_image,
            'recipe_url': recipe_url,
            'recipe_blog_url': recipe_blog_url,
            'recipe_ingredients_list': recipe_ingredients_list,
            'recipe_yield': recipe_yield,
            'recipe_calories': (recipe_calories / recipe_yield),
            'recipe_carbohydrates': (recipe_carbohydrates / recipe_yield),
            'recipe_protein': (recipe_protein) / recipe_yield,
            'recipe_fiber': (recipe_fiber / recipe_yield),
            'recipe_fat': (recipe_fat / recipe_yield),
            'recipe_potassium': (recipe_potassium / recipe_yield),
            'recipe_phosphorus': (recipe_phosphorus / recipe_yield),
            'recipe_sodium': (recipe_sodium / recipe_yield),
            'recipe_saturated_fat': (recipe_saturated_fat / recipe_yield),
            'recipe_iron': (recipe_iron / recipe_yield),
            'labels': labels
        }

        check_if_recipe_in_database = Recipe.query.filter_by(
            recipe_url=recipe_components['recipe_url']).first()

        # checks if recipe saved by user already in database by checking "recipes" table. If not, saves it.
        if not check_if_recipe_in_database:
            saved_recipe_to_add_to_db = Recipe(
                recipe_name=recipe_components['recipe_name'],
                recipe_image=recipe_components['recipe_image'],
                recipe_url=recipe_components['recipe_url'],
                blog_url=recipe_components['recipe_blog_url'],
                ingredients_list=recipe_components['recipe_ingredients_list'],
                recipe_yield=recipe_components['recipe_yield'],
                calories=recipe_components['recipe_calories'],
                carbohydrates=recipe_components['recipe_carbohydrates'],
                protein=recipe_components['recipe_protein'],
                fiber=recipe_components['recipe_fiber'],
                fat=recipe_components['recipe_fat'],
                potassium=recipe_components['recipe_potassium'],
                phosphorus=recipe_components['recipe_phosphorus'],
                sodium=recipe_components['recipe_sodium'],
                iron=recipe_components['recipe_iron'],
                saturated_fat=recipe_components['recipe_saturated_fat'])

            db.session.add(saved_recipe_to_add_to_db)
            db.session.commit()

            recipeid = saved_recipe_to_add_to_db.recipe_id

            recipe_components['recipeid'] = recipeid

            if recipe_components['labels']:

                for label in recipe_components['labels']:

                    saved_label_to_add = RecipeLabel(
                        recipe=saved_recipe_to_add_to_db, diet_label=label)

                    db.session.add(saved_label_to_add)
                db.session.commit()

        # after recipe is saved to database, will save ingredient in recipe_to_ingredients table, which contains recipe id as foreign key
        # this is to show an association between a recipe and its ingredient
            for ingredient in recipe_components['recipe_ingredients_list']:

                saved_ingredient_to_add = Ingredient(
                    ingredient_name=ingredient)
                db.session.add(saved_ingredient_to_add)

                recipe_to_ingredient_to_add = RecipeToIngredient(
                    recipe=saved_recipe_to_add_to_db,
                    ingredient=saved_ingredient_to_add)
                db.session.add(recipe_to_ingredient_to_add)

            db.session.commit()

        else:
            recipeid = check_if_recipe_in_database.recipe_id

            recipe_components['recipeid'] = recipeid

        # adds each recipe to a list, which will be sent to browser
        list_of_recipes.append(recipe_components)

    return render_template("recipesearchresults.html", recipes=list_of_recipes)
예제 #26
0
def add_meal_to_db(user_id, recipe_name, recipe_url, recipe_image, directions,
                   servings, calories, carbohydrates, fat, protein,
                   ingredients, cautions, diets):
    """Helper function."""

    old_recipe = Recipe.query.filter_by(recipe_url=recipe_url).first()

    new_cautions = ""
    for char in cautions:
        if char == "'":
            new_cautions += '"'
        else:
            new_cautions += char

    new_cautions_lst = json.loads(new_cautions)

    new_diets = ""
    for char in diets:
        if char == "'":
            new_diets += '"'
        else:
            new_diets += char

    new_diets_lst = json.loads(new_diets)

    if old_recipe is not None:
        new_recipe_obj = old_recipe
    else:
        new_recipe_obj = Recipe(recipe_name=recipe_name,
                                recipe_url=recipe_url,
                                recipe_image=recipe_image,
                                directions=directions,
                                servings=servings,
                                calories=calories,
                                carbohydrates=carbohydrates,
                                fat=fat,
                                protein=protein)
        db.session.add(new_recipe_obj)
        db.session.commit()

        for caution in new_cautions_lst:

            allergy = Allergy.query.filter_by(allergy_name=caution).first()

            new_caution_recipe_obj = RecipeAllergy(
                recipe_id=new_recipe_obj.recipe_id,
                allergy_id=allergy.allergy_id)
            db.session.add(new_caution_recipe_obj)

        for diet in new_diets_lst:

            diet = Diet.query.filter_by(diet_name=diet).first()

            new_diet_recipe_obj = RecipeDiet(
                recipe_id=new_recipe_obj.recipe_id, diet_id=diet.diet_id)
            db.session.add(new_diet_recipe_obj)

    db.session.commit()

    recipe = Recipe.query.filter_by(recipe_name=recipe_name).first()
    plan = Plan.query.filter_by(user_id=user_id).order_by(
        Plan.plan_id.desc()).first()

    plan_recipe_obj = PlanRecipe(plan_id=plan.plan_id,
                                 recipe_id=recipe.recipe_id)
    db.session.add(plan_recipe_obj)
    db.session.commit()

    new_ingredients = ""
    for char in ingredients:
        if char == "'":
            new_ingredients += '"'
        else:
            new_ingredients += char

    new_ingredients_dict = json.loads(new_ingredients)

    for ingredient in new_ingredients_dict:
        ingredient_name = ingredient["text"]
        amount = ingredient["weight"]

        ingredient = Ingredient.query.filter_by(
            ingredient_name=ingredient_name).first()
        if ingredient is None:
            new_ingredient_obj = Ingredient(ingredient_name=ingredient_name)
            db.session.add(new_ingredient_obj)
            db.session.commit()

            ingredient = Ingredient.query.filter_by(
                ingredient_name=ingredient_name).first()
            new_recipe_ingredient_obj = RecipeIngredient(
                recipe_id=recipe.recipe_id,
                ingredient_id=ingredient.ingredient_id,
                amount=amount)
            db.session.add(new_recipe_ingredient_obj)
            db.session.commit()