def get_search_results(userid): """Run search query and return results.""" search_query = request.args.get("searchQuery") if search_query != '': ##returns list of tuples ##index[0] = recipe_id ##index[1] = recipe_title ##index[2] = rank search_recipes = Recipe.run_search_query(userid, search_query) else: #gets all user recipes if the search query field is blank search_recipes = Recipe.get_user_recipe_list(userid) #creates dictionary from search results #key = recipeid #value = {dictionary of recipe title and userid} recipes_list = [] for recipe in search_recipes: recipe = list(recipe) recipes_list.append(recipe) return json.dumps(recipes_list)
def change_filters(): """ It searches recipes by filters. Gets a lists of filters. Returns: list of recipes (list of objects) list of cuisine (list of strings) list of sources (list of strings) list of categories (list of strings) list of levels (list of strings """ # Saves the parameters title = request.form("title") cuisine = request.form("cuisine") level = request.form("level") cat = request.form("cat") source = request.form("source") # Checks if the fields have a value and save them in a dictionary args = {} if title: args['title'] = title if cuisine: args['cuisine'] = cuisine if cat: args['cat_code'] = cat if level: args['skill_level'] = level if source: args['source'] = source # Calls the db functions to get lists of cuisine, sources, categories, titles cuisine = Recipe.getCuisineByFilter(**args) sources = Recipe.getSourcesByFilter(**args) categories = Recipe.getCatByFilter(**args) levels = Recipe.getLevelsByFilter(**args) titles = Recipe.getTitlesByFilter(**args) # Puts the data in a json format filters = { "cuisine": cuisine, "source" : sources, "categories": categories, "levels" : levels, "titles" : titles } return jsonify(filters)
def delete_recipe(recipeid): """deletes recipe for a given recipeid from database""" # Delete recipe when user clicks on a remove icon using model Class method Recipe.delete_existing_recipe(recipeid) Ingredient.delete_existing_ingredients(recipeid) flash("Your recipe has been deleted successfully") return redirect("/recipe-list")
def test_scrape_old_recipe(self): """ Test the scraping function when recipe is already in DB """ Recipe.deleteRecipeById(recipe_id=39) db.session.commit() result = self.client.post('/importRecipe', data={"url":"http://cooking.nytimes.com/recipes/1015348-spicy-red-pepper-cranberry-relish"}, follow_redirects=True) self.assertEqual(result.status_code, 200) self.assertIn('text/html', result.headers['Content-Type']) self.assertIn('Error: This recipe has already been loaded', result.data)
def delete_recipe(userid, recipeid): """Delete recipe from the db.""" #delete old recipe_hashtags Recipe_Hashtag.delete_old_recipe_hashtags(recipeid) #delete old ingredients Ingredient.delete_old_recipe_ingredients(recipeid) #delete old recipe Recipe.delete_recipe(recipeid) #flash message flash("You have successfully deleted your recipe.", "delete_recipe") return redirect("/myrecipes/%d" % userid)
def process_confirm_recipe_edit(recipeid): """Allows user to edit existing recipe and Save""" # get recipe object using recipeid recipe = Recipe.get_existing_recipe(recipeid) # get form variables and replace their value in the database for a given recipe recipe.recipe_id = recipeid recipe.title = request.form["title"] recipe.preparation = request.form["preparation"] recipe.yields = request.form["yields"] recipe.category_id = request.form["category_name"] recipe.image = request.form["image"] Ingredient.delete_existing_ingredients(recipeid) # get multiple ingredients information using getlist() method. ingredient_names = request.form.getlist('name') ingredient_quantities = request.form.getlist('quantity') ingredient_measures = request.form.getlist('measure') # iterate over range of ingredient_names and get user entered value for item, quantity and measure. for i in range(len(ingredient_names)): item = ingredient_names[i] quantity = ingredient_quantities[i] measure = ingredient_measures[i] Ingredient.create_ingredient(item=item, quantity=quantity, measure=measure, recipe_id=recipeid) db.session.commit() return redirect("/recipe-list")
def confirm_recipe_edit(userid, recipeid): """Make changes to the db to reflect the recipe edits.""" ####### Change Recipes Table ###### recipe_title = request.form.get("recipetitle") instructions = request.form.get("instructions") source = request.form.get("source") #update recipe table Recipe.edit_recipe(recipeid, recipe_title, instructions, source) ###### Change Tngredients Table ###### #delete old ingredients Ingredient.delete_old_recipe_ingredients(recipeid) #add new ingredients new_ingredient_count = Ingredient.get_ingredient_count(request.form) ingredients_dict = Ingredient.get_ingredients_to_add(new_ingredient_count, request.form) Ingredient.add_ingredient_to_recipe(new_ingredient_count, ingredients_dict, recipeid) ###### Change Hashtag Table ###### # no need to delete from hashtags table # just need to delete from the recipe_hashtags association table hashtags = request.form.get("hashtags") hashtag_list = re.sub('#', '', hashtags.lower()).split() # will add another row in hashtags table if a new hashtag # will get the hashtag_id if the hashtag already exists hashtag_id_list = Hashtag.get_hashtag_id(hashtag_list) ###### Recipe_Hashtag Table Section ###### #delete old recipe_hashtags Recipe_Hashtag.delete_old_recipe_hashtags(recipeid) # generate new recipe_hashtags Recipe_Hashtag.create_new_recipe_hashtag(recipeid, hashtag_id_list) ###### Tsvector Generation ###### Recipe.update_search_vector(recipeid) flash("You have successfully edited your recipe.", "edit_recipe") return redirect("/myrecipes/%d/recipe/%d" % (userid, recipeid))
def get(self, userid): """Get a list of user recipes. Returns JSON as {recipe_id: recipe_title}.""" user_recipes = Recipe.get_user_recipe_list(userid) recipes_dict = {} for r in user_recipes: recipes_dict[r[0]] = r[1] return recipes_dict
def show_view_recipe_page(recipeid): """Show view recipe page""" recipe = Recipe.get_existing_recipe(recipeid) ingredients = Ingredient.get_existing_ingredients(recipeid) return render_template("/display_recipe.html", recipe_id=recipeid, recipe=recipe, ingredients=ingredients)
def display_recipe(userid, recipeid): """Retrieves an individual recipe from db for display.""" recipe = Recipe.get_recipe(recipeid) ingredients = Ingredient.get_recipe_ingredients(recipeid) recipe_hashtags = Recipe_Hashtag.get_recipe_hashtags(recipeid) return render_template("recipe_info.html", recipe=recipe, ingredients=ingredients, recipe_hashtags=recipe_hashtags, userid=userid)
def show_prefilled_recipe_form(recipeid): """Show existing prefilled recipe form""" # recipe object recipe = Recipe.get_existing_recipe(recipeid) db_categories = Category.query.all() ingredients = Ingredient.get_existing_ingredients(recipeid) return render_template("/edit_recipe_form.html", recipe=recipe, db_categories=db_categories, ingredients=ingredients)
def recipe_list(): """ It searches all the Recipes: Returns: list of recipes (list of objects) list of cuisine (list of strings) list of sources (list of strings) list of categories (list of strings) list of levels (list of strings) """ # If user is logged in, search user's recipes. if 'User' in session: recipes = Recipe.getRecipesByUser(session['User']) cuisine = Recipe.getCuisineForRecipesByUser(session['User']) sources = Recipe.getSourceForRecipesByUser(session['User']) categories = Recipe.getCatForRecipesByUser(session['User']) levels = Recipe.getLevelsForRecipesByUser(session['User']) # If user is not logged in, return all recipes else: recipes = Recipe.getAllRecipes() cuisine = Recipe.getCuisineForRecipesByUser() sources = Recipe.getSourceForRecipesByUser() categories = Recipe.getCatForRecipesByUser() levels = Recipe.getLevelsForRecipesByUser() return render_template("recipe_list.html", recipes=recipes, levels=levels, cuisine=cuisine, sources=sources, categories=categories)
def add_new_recipe(): """Add new recipe to the database.""" try: ###### Recipe Table Section ###### user_id = session['User'] recipe_title = request.form.get("recipetitle") instructions = request.form.get("instructions") source = request.form.get("recipesource") new_recipe = Recipe.create_new_recipe(user_id, recipe_title, instructions, source) recipe_id = new_recipe.recipe_id ###### Ingredient Table Section ###### new_ingredient_count = Ingredient.get_ingredient_count(request.form) ingredients_dict = Ingredient.get_ingredients_to_add(new_ingredient_count, request.form) Ingredient.add_ingredient_to_recipe(new_ingredient_count, ingredients_dict, recipe_id) ###### Hashtag Table Section ###### hashtags = request.form.get("hashtags") # stardardizes format for hashtags hashtag_list = re.sub('#', '', hashtags.lower()).split() hashtag_id_list = Hashtag.get_hashtag_id(hashtag_list) ###### Recipe_Hashtag Table Section ###### Recipe_Hashtag.create_new_recipe_hashtag(recipe_id, hashtag_id_list) ###### Tsvector Generation ###### Recipe.update_search_vector(recipe_id) flash("You have successfully created your recipe. Hooray!", "create_recipe") return redirect("/myrecipes/%d" % user_id) except Exception: return redirect("/")
def get(self, query): """ Get a list of relevant recipes given a query. Returns JSON as {recipe id: [recipe title, relevance ranking]} """ search_results = Recipe.run_api_search_query(query) search_dict = {} for s in search_results: search_dict[s[0]] = [s[1], s[2]] return search_dict
def search_by_ingr(): """ Search recipes by ingredients """ # Gets the values of the ingredient ingredient = request.args.get("ingredient") if 'User' in session: recipes = Recipe.getRecipeByIngrByUser(ingredient, session['User']) else: recipes = Recipe.getRecipeByIngrByUser(ingredient) # Creates a list of recipe in a json format list_of_recipe_dictionaries = [r.json() for r in recipes] # Creates a dictionary of jsonified recipes recipe_info = { 'recipes': list_of_recipe_dictionaries } return jsonify(recipe_info)
def save_recipe_info(recipe): """Helper function to save the recipe selected to database""" recipe_id = recipe['uri'][-32:] recipe_entry = Recipe.query.filter_by(recipe_id=recipe_id).first() # add entry to recipes table if recipe does not already exist if not recipe_entry: new_recipe_entry = Recipe(recipe_image=recipe['image'], recipe_id=recipe_id, recipe_name=recipe['label'], recipe_url=recipe['url']) db.session.add(new_recipe_entry) db.session.commit() session['recipe_id'] = recipe_id
def add_recipe(): title = request.form.get("title") cuisine = request.form.get("cuisine") servings = request.form.get("servings") ready_in_minutes = request.form.get("ready_in_minutes") ingredients = request.form.get("ingredients") instructions = request.form.get("instructions") image = request.files.get("image") # del data["imageFile"] print(title) print(cuisine) print(ingredients) print(image) if image: result = cloudinary.uploader.upload(image, api_key=CLOUDINARY_KEY, api_secret=CLOUDINARY_KEY_SECRET, cloud_name='dplmlgxqq') image = result['secure_url'] else: image = None new_recipe = Recipe(title=title, cuisine=cuisine, servings=servings, ready_in_minutes=ready_in_minutes, ingredients=ingredients, instructions=instructions, image=image) db.session.add(new_recipe) db.session.commit() db.session.refresh(new_recipe) return { "success": True, "recipeAdded": { "recipe_id": new_recipe.recipe_id, "title": new_recipe.title, "cuisine": new_recipe.cuisine, "servings": new_recipe.servings, "readyInMinutes": new_recipe.ready_in_minutes, "ingredients": new_recipe.ingredients, "instructions": new_recipe.instructions, "image": new_recipe.image }, }
def load_recipes(recipes_filename): for row in open(recipes_filename): row = row.lstrip() row = row.rstrip() row = row.split("|") print 'ROW = {}'.format(row) recipe_id = row[0] recipe_name = row[1] recipe_image = row[2] recipe_url = row[3] recipe_blog_url = row[4] recipe_ingredients_list = row[5] recipe_yield = row[6] recipe_calories = row[7] recipe_carbohydrates = row[8] recipe_protein = row[9] recipe_fiber = row[10] recipe_fat = row[11] recipe_potassium = row[12] recipe_phosphorus = row[13] recipe_sodium = row[14] recipe_iron = row[15] recipe_saturated_fat = row[16] recipe = Recipe(recipe_id=int(recipe_id), recipe_name=recipe_name, recipe_image=recipe_image, recipe_url=recipe_url, blog_url=recipe_blog_url, ingredients_list=recipe_ingredients_list, recipe_yield=recipe_yield, calories=recipe_calories, carbohydrates=recipe_carbohydrates, protein=recipe_protein, fiber=recipe_fiber, fat=recipe_fat, potassium=recipe_potassium, phosphorus=recipe_phosphorus, sodium=recipe_sodium, iron=recipe_iron, saturated_fat=recipe_saturated_fat) db.session.add(recipe) db.session.commit()
def create_recipe(title, **kwargs): """Create and return a new recipe.""" recipe = Recipe(title=title, description=kwargs.get("description"), prep_time=kwargs.get("prep_time"), cook_time=kwargs.get("cook_time"), total_time=kwargs.get("total_time"), serving_qty=kwargs.get("serving_qty"), source=kwargs.get("source"), user_id=kwargs.get("user_id"), cuisine_id=kwargs.get("cuisine_id")) db.session.add(recipe) db.session.commit() return recipe
def edit_recipe(userid, recipeid): """Get a recipe from the db, and display it so the user can edit.""" recipe = Recipe.get_recipe(recipeid) ingredients = Ingredient.get_recipe_ingredients(recipeid) recipe_hashtags = Recipe_Hashtag.get_recipe_hashtags(recipeid) hashtag_list = Recipe_Hashtag.get_hashtag_names_for_recipe(recipe_hashtags) readable_hashtags = Hashtag.get_readable_hashtags(hashtag_list) recreated_hashtag_input = Hashtag.recreate_hashtag_input(readable_hashtags) return render_template("edit_recipe.html", recipe=recipe, ingredients=ingredients, userid=userid, recreated_hashtag_input=recreated_hashtag_input)
def add_recipe_to_db(): """Adds recipe to the database""" name = request.form["recipe_name"] instructions = request.form["instructions"] description = request.form["description"] recipe = Recipe(recipe_name=name, instructions=instructions, description=description, user_id=session["user_id"]) db.session.add(recipe) db.session.commit() new_recipe_id = Recipe.query.filter_by(description=description, user_id=session['user_id']).one() return render_template("create-recipe.html")
def processaddrecipe(): """processing adding a recipe""" name = request.form("recipename") instruction = request.form("instruction") preparationtime = request.form("preparationtime") dishtype = request.form("dishtype") recipeorigin = request.form("recipeorigin") # recipe= Recipe(name=name, instruction=instruction, dishtype=dishtype, preparationtime=preparationtime, recipeorigin=recipeorigin) recipe = Recipe(instructions=instruction, dishtype=dishtype, preparation_time=preparation_time, recipe_origin=recipe_origin, recipe_name=title) db.session.add(recipe) db.session.commit()
def load_recipes(filepath, user=999, share="yes"): tree = ET.parse(filepath) root = tree.getroot() for recipe in root: name = recipe.find('NAME').text if Recipe.query.filter_by(name=name).first(): return "error", name break source = el_find_text(recipe, 'SOURCE', "") user_id = user public = share style = [ elem.find('NAME').text for elem in recipe.iter() if elem.tag == "STYLE" ] style_name = style[0] notes = el_find_text(recipe, 'NOTES', "") batch_size = el_find_text(recipe, 'BATCH_SIZE', "L") batch_units = "L" # srm = 0 new_recipe = Recipe( name=name, source=source, user_id=user_id, public=public, notes=notes, batch_size=batch_size, batch_units=batch_units, style_name=style_name, # srm=srm ) db.session.add(new_recipe) db.session.commit() load_hops_ins(filepath) load_ferm_ins(filepath) load_ext_ins(filepath) load_misc_ins(filepath) load_yeast_ins(filepath) recipe_id = Recipe.query.filter_by(name=name).one().recipe_id # calc_color(recipe_id, batch_size, batch_units) return "success", name
def load_recipes(recipe_name, recipe_api_id, time_in_min, site_name, src_url, img_url): """Load recipes into database.""" print "Recipe" if not Recipe.query.filter_by(recipe_name=recipe_name).all(): site_id = Website.query.filter_by(site_name=site_name).first().site_id recipe = Recipe(recipe_name=recipe_name, time_in_min=time_in_min, recipe_api_id=recipe_api_id, src_url=src_url, img_url=img_url, site_id=site_id) db.session.add(recipe) db.session.commit()
def update_user_recipes(): """ Keeps track of user's selected recipes.""" recipe_id = request.form.get("recipe_id") recipe = Recipe.query.get(int(recipe_id)) if not recipe: new_recipe = Recipe(recipe_id=recipe_id, ) db.session.add(new_recipe) db.session.commit() new_user_recipe = UserRecipe( user_id=session['user_id'], recipe_id=recipe_id, status='needs_ingredients', ) db.session.add(new_user_recipe) db.session.commit() return jsonify({'recipe_id': recipe_id})
def add_recipe(recipe_id): """ Adds recipe to Recipes table, which also populates the following tables: Ingredient, Aisle, Cuisine, RecipeIngredient. Returns new Recipe object back to server.""" # Get info from API and store as json info_response = api_calls.recipe_info(recipe_id) # Add new recipe to DB new_recipe = Recipe(recipe_id=recipe_id, recipe_name=info_response['title'], img_url=info_response['image'], instructions=info_response['instructions']) db.session.add(new_recipe) db.session.commit() ingredients_info = info_response['extendedIngredients'] return new_recipe
def create_recipe(create_recipe_name, source_url, recipe_course, prep_time, cook_time, total_recipe_time, ingredients, recipe_description, servings, directions, image, user_id): create_recipe = Recipe(create_recipe_name=create_recipe_name, source_url=source_url, recipe_course=recipe_course, prep_time=prep_time, cook_time=cook_time, total_recipe_time=total_recipe_time, ingredients=ingredients, recipe_description=recipe_description, servings=servings, directions=directions, image=image, user_id=user_id) db.session.add(create_recipe) db.session.commit() return create_recipe
def process_recipe_form(): """Process recipe form to add new recipe to the database.""" print "request.form: ", request.form # get recipe form variables. userid = session["user_id"] title = request.form["title"] preparation = request.form["preparation"] yields = request.form["yields"] category_id = request.form["category_name"] image = request.form["image"] # get multiple ingredients information using getlist() method. ingredient_names = request.form.getlist('name') ingredient_quantities = request.form.getlist('quantity') ingredient_measures = request.form.getlist('measure') # add above recipe information to database using create_recipe() method from model Class Recipe. new_recipe = Recipe.create_recipe(title, category_id, userid, preparation, yields, image) # get recipe id using get_recipe_id() method from model Class Recipe. # recipe_id = Recipe.get_recipe_id(title, userid) # this is a bug, don't use this line. recipe_id = new_recipe.recipe_id # iterate over range of ingredient_names and get user entered value for item, quantity and measure. for i in range(len(ingredient_names)): item = ingredient_names[i] quantity = ingredient_quantities[i] measure = ingredient_measures[i] #add ingredient information to database using create_ingredient() method from model Class Ingredient. Ingredient.create_ingredient(item=item, quantity=quantity, measure=measure, recipe_id=recipe_id) return redirect("/recipe-list")
def get_suggestions(): """Get user data for typeahead suggestions.""" userid = session['User'] #### Hashtag Data #### hashtag_data = Hashtag.get_hashtags_by_user(userid) hashtag_list = [h[0] for h in hashtag_data] #### Recipe Data #### recipe_data = Recipe.get_user_recipe_list(userid) recipe_list = [r[1] for r in recipe_data] #### Ingredient Data #### ingredient_data = Ingredient.get_ingredients_by_user(userid) # convert to set then back to list to remove duplicates ingredient_list = list(set([i[0] for i in ingredient_data])) #### Combined Data #### data_list = hashtag_list + recipe_list + ingredient_list return jsonify({"userdata": data_list})
def save_recipe(): """Stores a saved recipe into database.""" # make a new record in the plan table start = request.form.get("start") plan = Plan( start=start, user_id=session['user_id'], ) db.session.add(plan) db.session.commit() recipes = [] plan.recipes = [] for i in range(1, 6): recipes.append( ast.literal_eval(request.form.get("recipe-{}".format(i)))) recipe = db.session.query(Recipe).filter_by( recipe_id=recipes[i - 1]["id"]).first() if recipe is not None: recipe.num_saved += 1 else: recipe = Recipe(recipe_id=recipes[i - 1]["id"], title=recipes[i - 1]["title"], url=recipes[i - 1]["url"], image=recipes[i - 1]["image"], prep_time=recipes[i - 1]["prepTime"], num_saved=1, fat=recipes[i - 1]["fat"], carbohydrates=recipes[i - 1]["carbs"], protein=recipes[i - 1]["protein"]) db.session.add(recipe) plan.recipes.append(recipe) db.session.commit() return redirect("/mymeals")
def fav_recipes(): """Favorite recipe and store URL in Recipe table""" # get user_id from session user_id = session['user'] #Use Ajax request to get data title = request.args.get("title") url = request.args.get("fav-url") img = request.args.get("img") # Check user info against database recipe_query = Recipe.query.filter_by(user_id=user_id, title=title).first() if recipe_query == None: recipe = Recipe(user_id=user_id, title=title, url=url, img=img) db.session.add(recipe) db.session.commit() return jsonify('Recipe added to favorites!') else: return jsonify('Recipe already in favorites!')
def likes(recipe_id): if session.get("user_id"): recipe_id = recipe_id user_id = session.get("user_id") recipeinfomation = recipeinfo(recipe_id) title = recipeinfomation["title"] image = recipeinfomation["image"] likes = recipeinfomation["likes"] instruction = recipeinfomation["instruction"] video = recipeinfomation["video"] recipe = Recipe.query.filter_by(recipe_id=recipe_id).first() userfavoriterecipe = UserFavoriteRecipe.query.filter_by( user_id=user_id, recipe_id=recipe_id).first() if userfavoriterecipe is None: if not recipe: recipe = Recipe(recipe_id=recipe_id, instructions=instruction, recipe_name=title, image=image) try: db.session.add(recipe) db.session.commit() except Exception: pass print("====user id", user_id, recipe_id) userfavoriterecipe = UserFavoriteRecipe(user_id=user_id, recipe_id=recipe_id) db.session.add(userfavoriterecipe) db.session.commit() return redirect(f"/recipes/{recipe_id}") return redirect('/signin')
def create_new_recipe(recipe_name, source_name, website, directions, image, servings, ingredients): """Create and return new recipes, add ingredients to database if not there, and add associated ingredients in recipes where ingredients is a list of dictionary objects.""" # Add recipe to db current_recipe = Recipe(recipe_name=recipe_name.title(), source_name=string.capwords(source_name), website=website, directions=directions, image=image, servings=servings) db.session.add(current_recipe) db.session.commit() # get a list of existing ingredients in db and commit ingredients from recipe to db if not already in. existing_ingredients = all_ingredients_by_name() # REVISIT? current_ingredient_objects = all_ingredients() current_recipe_id = current_recipe.recipe_id for ingredient in ingredients: #ingredient is a dictionary name = ingredient.get('ingredient_name') #access key-value pair if name not in existing_ingredients: ingredient_id = add_new_ingredient(name).ingredient_id else: ingredient_obj = Ingredient.query.filter_by( ingredient_name=name).first() # QUERYING EVERYTIME. REVISIT ingredient_id = ingredient_obj.ingredient_id ##### Doesn't account for any attributes of the ingredient nor ensure case consistency amount = ingredient.get('amount', None) metric = ingredient.get('metric', None) preparation = ingredient.get('preparation', None) add_needed_ingredient(current_recipe_id, ingredient_id, amount, metric, preparation) return current_recipe
def load_recipe(): """Load recipes into database.""" print("Recipes") for i, row in enumerate(open("seed_data/recipe.seed.txt")): row = row.rstrip() user_id, recipe_id, recipe_name, recipe_link = row.split("\t") user_id = int(user_id) recipe_id = int(recipe_id) recipe_link = str(recipe_link) recipe = Recipe(user_id=user_id, recipe_id=recipe_id, recipe_name=recipe_name recipe_link=recipe_link) # We need to add to the session or it won't ever be stored db.session.add(recipe) # provide some sense of progress if i % 1000 == 0: print(i) # An optimization: if we commit after every add, the database # will do a lot of work committing each record. However, if we # wait until the end, on computers with smaller amounts of # memory, it might thrash around. By committing every 1,000th # add, we'll strike a good balance. # Once we're done, we should commit our work db.session.commit()
def tearDown(self):# It runs after each test print 'doing my teardown' User.query.filter_by(user_id=2).delete() Recipe.deleteRecipeById(recipe_id=39) db.session.commit()
def load_recipes(): """ Load recipes into RECIPES table """ print "Adding Recipes" urls_plus_ingredients = {} qty_data = set() urls_plus_categories = {} raw_tags = set() urls_plus_difficulty = {} difficulty_types = set() for data_file in data_files: with open(data_file) as file: recipe_lines = json.load(file) # Delete all rows in table, so sample table can be created repeatedly with # new data and no duplicates # Recipe.query.delete() for line in recipe_lines: if line['url'] == "http://www.foodnetwork.com/error-page/500": pass else: url = line['url'] difficulty = "".join(line['difficulty']) recipe_name = line['recipe_name'] ######################################################################## # CATEGORY TAGS: Transfer scraped category arrays to a set to return # for further processing in LOAD_TAGS function. urls_plus_categories[url] = set() for item in line['category_tags']: if len(item) > 0: raw_tags.add(item) urls_plus_categories[url].add(item) ######################################################################## # DIFFICULTY LEVELS: Transfer scraped difficulty strings to a set to return # for further processing in LOAD_DIFFICULTY function. if difficulty != 'N/A': urls_plus_difficulty[url] = difficulty difficulty_types.add(difficulty) ######################################################################## # SERVINGS: Split servings strings into 2 columns: servings_num (integer) # and servings_unit (text of serving unit/quantity) servings = line['servings'] text_servings = line['servings'] if servings == 'N/A': servings_unit = None servings_num = None text_servings = None else: servings = re.sub(r" ?\([^)]+\)", "", servings) num = [i for i in servings.split() if i.isnumeric()] unit = [ i for i in servings.lower().split() if (i.isnumeric() is False) and (i in accepted_units) ] if num == []: servings_num = None else: servings_num = num[0] if unit == []: servings_unit = None else: servings_unit = " ".join(unit) ######################################################################## # INGREDIENTS: Populate value as an array; split into 2 additional columns # of dict ingredient: qty (converted to grams) & text ingredients without # amounts # TEXT INGREDIENTS (written as in original text) text_ingredients = line['ingredients'] # INGREDIENTS NAMES (cleaned of measures, numeric amounts, commentary) urls_plus_ingredients[url] = set() ingredient_amounts = {} ingredient_units = {} if len(line['ingredients']) > 0: for item in line['ingredients']: item = re.sub(r" ?\([^)]+\)", "", item) item = re.sub(r"\b-\b", " ", item) item = item.lower().split(" ") amt = [ i for i in item if i.isnumeric() or i in fraction_conversions ] if len(amt) > 0: if amt[0] in fraction_conversions: amt = [fraction_conversions[amt[0]]] if len(amt) > 1: if amt[1] in fraction_conversions: amt = [ float(amt[0]) + fraction_conversions[amt[1]] ] else: amt = amt[:1] else: amt = None unit = [i for i in item if (i in accepted_measures)] if len(unit) > 0: unit = accepted_measures[unit[0]] else: unit = None item = [ i for i in item if ((i.isnumeric() is False) and (len(i) > 0) and ( i not in measure_names and i not in descriptors and i not in fractions)) ] item = " ".join(item).rstrip().encode('utf-8') item = item.split(',') item = item[0] if len(item) > 0: qty_data.add(item) urls_plus_ingredients[url].add(item) # INGREDIENTS QTY (uses cleaned ingredient names as keys; converts # amounts to grams for consistency; also tracks corresponding units) if item not in ingredient_amounts: if amt is not None and len(amt) > 0: if unit is not None: amt = amt[0] if type( amt ) != float and not amt.isdigit(): if len(amt) > 1: amt = numeric( amt[0]) + numeric(amt[1]) else: amt = numeric(amt) ingredient_amounts[item] = round( (float(amt) * gram_conversions[unit]), 2) else: amt = amt[0] if type( amt ) != float and not amt.isdigit(): if len(amt) > 1: amt = numeric( amt[0]) + numeric(amt[1]) else: amt = numeric(amt) ingredient_amounts[item] = amt else: ingredient_amounts[item] = None # Add ingredient units to ingredient_units dictionary if item not in ingredient_units: if unit is not None: ingredient_units[item] = unit ######################################################################## # SPECIAL EQUIPMENT: Populate with null if null; clean formatting where # not null if len(line['special_equipment']) == 0: special_equipment = None else: for i in range(len(line['special_equipment'])): s = line['special_equipment'][i].lstrip() prefix = s[:19] if prefix == "Special equipment: ": line['special_equipment'][i] = s[19:].rstrip() special_equipment = line['special_equipment'] ######################################################################## # PREP INSTRUCTIONS: Clean formatting & add cleaned list of <p> contents stripped_prep = [] for p in line['preparation']: if len(p.lstrip().rstrip()) > 0: stripped_prep.append(p.lstrip().rstrip()) preparation = stripped_prep ######################################################################## # ALL RECIPE TIMES: Populate with null if null; if not null, typecast # into sql interval type times = {'hr': 'hours', 'min': 'minutes'} # TOTAL TIME if line['total_time'] == 'N/A': total_time = None else: total_time = "" time = line['total_time'].split() for t in time: if t.isnumeric(): total_time = total_time + t else: total_time = total_time + " {} ".format(times[t]) # COOK TIME if line['cook_time'] == 'N/A': cook_time = None else: cook_time = "" time = line['cook_time'].split() for t in time: if t.isnumeric(): cook_time = cook_time + t else: cook_time = cook_time + " {} ".format(times[t]) # PREP TIME if line['prep_time'] == 'N/A': prep_time = None else: prep_time = "" time = line['prep_time'].split() for t in time: if t.isnumeric(): prep_time = prep_time + t else: prep_time = prep_time + " {} ".format(times[t]) # ACTIVE TIME if line['active_time'] == 'N/A': active_time = None else: active_time = "" time = line['active_time'].split() for t in time: if t.isnumeric(): active_time = active_time + t else: active_time = active_time + " {} ".format(times[t]) # INACTIVE TIME if line['inactive_time'] == 'N/A': inactive_time = None else: inactive_time = "" time = line['inactive_time'].split() for t in time: if t.isnumeric(): inactive_time = inactive_time + t else: inactive_time = inactive_time + " {} ".format( times[t]) ######################################################################## # PHOTO URL: Check if photo URL exists or has default "N/A" value # assigned from scrapy. If N/A, rebinds variable to python/jinja # parsable "None" photo_url = line['photo_url'] if photo_url == 'http:N/A': photo_url = None ######################################################################## # RECIPE AUTHOR: Check if Recipe Author exists or has default "N/A" # value assigned from scrapy. If N/A, rebinds variable to # python/jinja parsable "None" recipe_author = line['recipe_author'] if recipe_author == 'N/A': recipe_author = None ######################################################################## # CREATE OBJECT: Declare object, declare all column values, add object # to database, rise & repeat. recipe = Recipe(recipe_name=recipe_name, recipe_author=recipe_author, servings_num=servings_num, servings_unit=servings_unit, text_servings=text_servings, special_equipment=special_equipment, text_ingredients=text_ingredients, ingredient_amounts=ingredient_amounts, ingredient_units=ingredient_units, preparation=preparation, total_time=total_time, prep_time=prep_time, cook_time=cook_time, active_time=active_time, inactive_time=inactive_time, photo_url=photo_url, recipe_url=url) db.session.add(recipe) ############################################################################ # COMMIT: Commit all changes (objects added) to database. db.session.commit() return [ urls_plus_ingredients, qty_data, urls_plus_categories, raw_tags, urls_plus_difficulty, difficulty_types ]
def enter_recipe(): """ Get - display add recipe. Post - Add recipe and edit recipe pages info routed here for processing and uploading to db """ if request.method == "POST": data = request.get_json() grains = data['grains'] extracts = data['extracts'] hops = data['hops'] miscs = data['miscs'] yeasts = data['yeasts'] # Recipe values name = data["name"] user_id = session["user_id"] source = data["source"] public = data["share"] style_name = data["style"] notes = data["notes"] batch_size = data["batch_size"] batch_units = data["units"] new_recipe = Recipe(name=name, source=source, user_id=user_id, public=public, notes=notes, style_name=style_name, batch_size=batch_size, batch_units=batch_units) db.session.add(new_recipe) db.session.commit() # Recipe_id will be used in all instructions uploads recipe_id = Recipe.query.filter_by(name=name, user_id=user_id)[0].recipe_id # Grain Instructions for i in range(0, len(data['grains']), 3): grain_name = grains[i]["value"] ferm_id = Fermentable.query.filter_by(name=grain_name)[0].id grain_amount = grains[i + 1]["value"] grain_units = grains[i + 2]["value"] new_fermins = FermIns( recipe_id=recipe_id, ferm_id=ferm_id, amount=grain_amount, units=grain_units, ) db.session.add(new_fermins) db.session.commit() # Extract Instructions if extracts: for i in range(0, len(data['extracts']), 3): extract_name = extracts[i]["value"] extract_id = Extract.query.filter_by(name=extract_name)[0].id extract_amount = extracts[i + 1]["value"] extract_units = extracts[i + 2]["value"] new_extins = ExtIns(recipe_id=recipe_id, extract_id=extract_id, amount=extract_amount, units=extract_units) db.session.add(new_extins) db.session.commit() # Hops Instructions for i in range(0, len(data['hops']), 6): hop_name = hops[i]["value"] hop_id = Hop.query.filter_by(name=hop_name)[0].hop_id hop_amount = hops[i + 1]["value"] hop_units = hops[i + 2]["value"] hop_phase = hops[i + 3]["value"] time = hops[i + 4]["value"] kind = hops[i + 5]["value"] new_hopsins = HopIns(recipe_id=recipe_id, hop_id=hop_id, amount=hop_amount, phase=hop_phase, time=time, kind=kind) db.session.add(new_hopsins) db.session.commit() # Misc Instructions if miscs != []: for i in range(0, len(data['miscs']), 5): misc_name = miscs[i]["value"] misc_id = Misc.query.filter_by(name=misc_name)[0].misc_id misc_amount = miscs[i + 1]["value"] misc_units = miscs[i + 2]["value"] misc_phase = miscs[i + 3]["value"] misc_time = miscs[i + 4]["value"] new_miscins = MiscIns(recipe_id=recipe_id, misc_id=misc_id, phase=misc_phase, amount=misc_amount, time=misc_time, units=misc_units) db.session.add(new_miscins) db.session.commit() # Yeast Instructions for i in range(0, len(data['yeasts']), 4): yeast_name = yeasts[i]["value"] yeast_id = Yeast.query.filter_by(name=yeast_name)[0].yeast_id yeast_amount = yeasts[i + 1]["value"] yeast_units = yeasts[i + 2]["value"] yeast_phase = yeasts[i + 3]["value"] new_yeastins = YeastIns(recipe_id=recipe_id, yeast_id=yeast_id, amount=yeast_amount, units=yeast_units, phase=yeast_phase) db.session.add(new_yeastins) db.session.commit message = "Your recipe has been added." return message grain_choice, extract_choice, hop_choice, misc_choice, yeast_choice, selectlist_styles = feed_recipe_form( ) return render_template("recipeform.html", selectlist_styles=selectlist_styles, grain_choice=grain_choice, hop_choice=hop_choice, extract_choice=extract_choice, misc_choice=misc_choice, yeast_choice=yeast_choice)
def addRecipe(img_file, title, description, cat_code, servings, cooktime, skillLevel, cuisine, ingredients, steps, user): """ It adds a recipe, ingredients, recipe steps, recipe_user""" try: # Saves the img file in the directory filename = img_file print "IMG_FILE" ,img_file # If img is not from a website # if img_file and allowed_file(img_file.filename) and 'http' not in img_file: # filename = secure_filename(img_file.filename) # print "FILENAME" , filename # img_file.save(os.path.join(UPLOAD_FOLDER, filename)) # Add recipe in 'recipes' Table Recipe.addRecipe(title, description, filename, cat_code, servings, cooktime, skillLevel,cuisine) # Finds the recipe_id recipeIds= db.session.query(func.max(Recipe.recipe_id)).one() recipeFk = recipeIds[0] print "RECIPE ID: ",recipeFk # ingredients = ingredients print "INGREDIENTS LIST", ingredients for ingredient in ingredients: name = ingredient["name"] qty = ingredient["qty"] unit = ingredient["unit"] print "INGREDIENT UNICODE", ingredient # Add ingredients in 'RecipeIngredient' RecipeIngredient.addIngredients(recipeFk, name, qty, unit) # Add ingredients in 'Ingredients' Ingredient.addIngredients(name) for i in range(len(steps)): print "STEP%d" % i print "step value: ", steps[i] # Add steps in 'recipe_step' RecipeStep.addRecipeStep(recipeFk,i+1,steps[i]) if 'User' in session: RecipeUser.addRecipeForUser(recipeFk,session['User']) db.session.commit() # Recipe.updateRecipeImg(title=title, cat_code=cat_code) message = { 'msg': "Recipe successfully added", 'recipeid': recipeFk } return recipeFk except Exception, error: return "Error: %s" % error
def delete_recipe(recipeid): Recipe.deleteRecipeById(recipeid) db.session.commit() return redirect ("/recipes")
print('All available ingredients:') for ingredient in Ingredient.list_all_ingredients(man): print(f'\t{ingredient.iname}') # Create some recipes pancakes = Recipe.register_recipe( man, # RecipeManager 'Cakes', # name 5, # servings 20, # prep time ['Pan', 'Stove'], # equipment user, # recipe owner (should be a User) { # Ingredients flour: 1.25, water: 1.25, sugar: 2, baking_pow: 2, salt: 0.5, oil: 1 }, [ # steps 'Combine dry ingredients & mix', 'Combine wet ingredients and whisk', 'Combine wet and dry ingredients and stir briefly', 'Dolop onto pan and cook, flipping partway through' ]) cookies = Recipe.register_recipe( man, 'Chocolate Chip Cookies', 36, 25, ['oven', 'baking sheet'], user, { oil: 3.6, brown_sugar: 1,
def add_new_recipe(): """Add new recipe to db.""" target = os.path.join(APP_ROOT, 'uploads/') if not os.path.isdir(target): os.mkdir(target) for upload in request.files.getlist('file'): filename = upload.filename #Verifys if files are supported ext = os.path.splitext(filename)[1] #if ext in ALLOWED_EXTENSIONS: #flash('File extension supported.') #else: #flash('Upload a valid file.') destination = "/".join([target, filename]) upload.save(destination) user_id = session['logged_in_user'] img_url = "/uploads/" + filename title = request.form.get('title') occasion = request.form.get('occasion').lower() occasion_check = Occasion.query.filter_by(oname=occasion).first() if not occasion_check: new_occasion = Occasion(oname=occasion) db.session.add(new_occasion) description = request.form.get('description') ingridients = request.form.getlist('ingridients') instructions = request.form.get('instructions') tools = request.form.getlist('tools') new_recipe = Recipe(img_url=img_url, rname=title, style=description, instructions=instructions, user_id=user_id) db.session.add(new_recipe) db.session.commit() if not occasion_check: new_recipe_occasion = RecipeOccasion( recipe_id=new_recipe.recipe_id, occasion_id=new_occasion.occasion_id) else: new_recipe_occasion = RecipeOccasion( recipe_id=new_recipe.recipe_id, occasion_id=occasion_check.occasion_id) db.session.add(new_recipe_occasion) for ingridient in ingridients: ingreident_obj = Ingridient.query.filter_by(iname=ingridient).first() recipe_ingrident = RecipeIngridient( ingridient_id=ingreident_obj.ingridient_id, recipe_id=new_recipe.recipe_id) db.session.add(recipe_ingrident) for tool in tools: tool_obj = Tool.query.filter_by(tname=tool).first() recipe_tool = RecipeTool(tool_id=tool_obj.tool_id, recipe_id=new_recipe.recipe_id) db.session.add(recipe_tool) db.session.commit() recipe = Recipe.query.filter_by(rname=title, style=description).first() return render_template('new_recipe.html', img_name=filename, recipe=recipe)
def getPlanner(date=None, num=None): """ Gets the list of meals planned """ start_date = '' # It sets the START DATE. if date and num =='-': start_date = datetime.strptime(date,'%Y-%m-%d %H:%M:%S.%f') - timedelta(days=7) elif date and num == '+': start_date = datetime.strptime(date,'%Y-%m-%d %H:%M:%S.%f') + timedelta(days=7) if not start_date: start_date = datetime.today() # It sets the END DATE end_date = start_date + timedelta(days=6) currentWeek = start_date.strftime("%W") week_days = [] meal_list = [] meal_days = [] if 'User' in session: recipes = Recipe.getRecipesByUser(session['User']) cuisine = Recipe.getCuisineForRecipesByUser(session['User']) categories = Recipe.getCatForRecipesByUser(session['User']) for i in range(7): week_days.append(int(start_date.strftime("%w")) + i) for i in range(7): mealsPlanned='' date = start_date + timedelta(days=i) # mealsPlanned = Meals.getMealsByDate(date, session['User']) b_meals = Meals.getMealsByDateByType(date, session['User'], 'breakfast') l_meals = Meals.getMealsByDateByType(date, session['User'], 'lunch') d_meals = Meals.getMealsByDateByType(date, session['User'], 'dinner') s_meals = Meals.getMealsByDateByType(date, session['User'], 'snack') # print "BREAKFAST",b_meals meal_list.append({"date": date, "b_meals":b_meals, "l_meals":l_meals, "d_meals":d_meals, "s_meals":s_meals}) print 'DATA', date return render_template("planner.html", meals_list=meal_list, week_days=week_days, start_date=start_date, end_date=end_date, recipes=recipes, cuisine=cuisine, categories=categories) else: flash("You need to sign in") return render_template("error.html",url="/planner")
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)
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()
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()
# flask imports from flask import Flask, render_template, request, redirect, url_for # SQLAlchemy from model import Base, Recipe from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # setup app = Flask(__name__) engine = create_engine('sqlite:///project.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() Base.metadata.create_all() recipe1 = Recipe(owner = "Gilead", title ="amazing flour",country= "USA", ingredients = "flour", picture_url= "coming up", description = "mix flour") session.add(recipe1) session.commit()
def display_recipe_list(userid): """Display a list of recipes for a given user.""" user_recipes = Recipe.get_user_recipe_list(userid) return render_template("recipe_list.html", userid=userid, user_recipes=user_recipes)
def tearDown(self): # It runs after each test print 'doing my teardown' User.query.filter_by(user_id=2).delete() Recipe.deleteRecipeById(recipe_id=39) db.session.commit()
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({})