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 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): """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 update_edited_cart(userid, cartid): """Update the cart_ingredients table to reflect edited changes.""" # delete old cart ingredients Cart_Ingredient.delete_old_cart_ingredients(cartid) # get and format the new cart ingredients edited_cart_ings = Ingredient.get_edited_cart_ings(request.form) # add new cart ingredients to the ingredients table and cart_ingredients table Ingredient.add_edited_cart_ings_to_db(edited_cart_ings, cartid) return redirect("/myrecipes/%d/cart/%d" % (userid, cartid))
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()
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()
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 add_ingredient(name, location): """add ingredient""" ingredient = Ingredient(name=name, location=location) db.session.add(ingredient) db.session.commit() return ingredient
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()
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})
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()
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
def getIngredient(key): client = memcache.Client() ingredient = client.get(key) if ingredient == None: ingredientDb = Ingredient.get(key) if ingredientDb != None: ingredient = createIngredientDb(ingredientDb) client.set(key, ingredient) return client.get(key)
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)
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 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 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()
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)
def add_recipe_to_cart(recipeid, userid): """Add ingredients from a given recipe to grocery cart.""" recipe_ingredients = Ingredient.get_recipe_ingredients(recipeid) for ingredient in recipe_ingredients: Cart_Ingredient.create_new_cart_ingredient(session['Cart'], ingredient.ingredient_id) flash("You have successfully added your recipe to your grocery cart.", "cart_add") return redirect("/myrecipes/%d/cart/%d" % (userid, session['Cart']))
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'])
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 getIngredients(): client = memcache.Client() ingredients = client.get(INGREDIENTS_KEY) if ingredients == None: ingredients = [] ingredientsDb = Ingredient.gql("ORDER BY name") if ingredientsDb != None: for ingredientDb in ingredientsDb: ingredient = createIngredientDb(ingredientDb) ingredients.append(ingredient) client.set(INGREDIENTS_KEY, ingredients) return ingredients
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
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 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 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 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()
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
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)
def get(self, userid): """ Get a list of user ingredients and the number of times they appear in a user's recipes. Returns JSON as {ingredient_name: count} """ user_ings = Ingredient.get_ingredient_counts_by_user(userid) ingredients_dict = {} for i in user_ings: ingredients_dict[i[0]] = i[1] return ingredients_dict
def post(self): if not isUserCook(self): self.redirect("/") return category = db.get(self.request.get('ingredientCategoryKey')) ingredient = Ingredient() ingredient.name = self.request.get('ingredient_name') ingredient.category = category ingredient.put() addIngredient(ingredient) self.redirect('/ingredient?ingredientKey=%s&source=%s' % (ingredient.key(), category.key()))
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()
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 post(self): if not isUserCook(self): self.redirect("/") return #Check if ingredient exists ingredientKey=self.request.get('ingredientKey') if ((ingredientKey != None) and (ingredientKey != "")): #Ingredient must exist ingredient = Ingredient.get(ingredientKey) ingredientCategoryKey=self.request.get('ingredientCategoryKey') if ((ingredientCategoryKey != None) and (ingredientCategoryKey != "")): ingredient.category = IngredientCategory.get(ingredientCategoryKey) else: ingredient.category = None price=self.request.get('price') energy=self.request.get('energy') protein=self.request.get('protein') carbs=self.request.get('carbs') fat=self.request.get('fat') fiber=self.request.get('fiber') if ((price != None) and (price != "")): ingredient.price = float(price) if ((energy != None) and (energy != "")): ingredient.energy = float(energy) if ((protein != None) and (protein != "")): ingredient.protein = float(protein) if ((carbs != None) and (carbs != "")): ingredient.carbs = float(carbs) if ((fat != None) and (fat != "")): ingredient.fat = float(fat) if ((fiber != None) and (fiber != "")): ingredient.fiber = float(self.request.get('fiber')) ingredient.put() modifyIngredient(ingredient) sourceKey=self.request.get('source') if ((sourceKey == ingredientCategoryKey) and (sourceKey!=None) and (sourceKey != "")): if ingredient.category != None: self.redirect('/ingredientCategory?ingredientCategoryKey=%s' % ingredient.category.key()) return else: self.redirect('/ingredient') return else: self.redirect('/ingredient') return else: ingredient = Ingredient() ingredient.name = self.request.get('ingredient_name') ingredient.put() addIngredient(ingredient) self.redirect('/ingredient?ingredientKey=%s' % ingredient.key())
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()
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()
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 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 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