Exemplo n.º 1
0
def add_recipe():
    if request.query_string[:4] == "url=":
       app.logger.info("Adding from source:  " + request.query_string[4:])
       form = fillout_form( request.query_string[4:] )
    else:
        form = RecipeForm(request.form)
    if request.method == "POST":
        if form.validate_on_submit():
            app.logger.info("Adding a new Recipe")
            recipe=Recipe()
            form.populate_obj(recipe)
            if len(request.files) > 0:
                app.logger.debug("Image uploaded")
                req = request
                filename = req.files['image_file'].filename
                recipe_name = recipe.recipe_name
                recipe.image_path = upload_image(req, filename, recipe_name)
                if recipe.image_path is None:
                    flash("Error uploading image")
            recipe.user_id = 1
            recipe.timestamp = date.today()
            db.session.add(recipe)
            db.session.commit()
            
            new_rec = Recipe.query.filter(Recipe.recipe_name==  str(recipe.recipe_name)).first()
            #import pdb; pdb.set_trace()
            return redirect(url_for('view_recipe', id=new_rec.id))
        else:
            flash('Invalid data')
            return render_template('recipe_form.html',form = form, title="Add A New Recipe")
    elif request.method != "POST":
        return render_template('recipe_form.html',form = form, title="Add A New Recipe")
    return redirect(url_for('add_recipe'))
Exemplo n.º 2
0
def create_recipe():
    """Create new recipe"""
    if 'username' not in session:
        flash("Please log in to view this page", "danger")
        return redirect('/login')

    form = RecipeForm()
    username = session['username']

    if form.validate_on_submit():
        title = form.title.data
        image = form.image.data
        calories = form.calories.data
        total_yield = form.total_yield.data
        time = form.time.data
        ingredients = form.ingredients.data

        user = User.query.get_or_404(username)
        recipe = Recipe(title=title,
                        image=image,
                        url=None,
                        calories=calories,
                        total_yield=total_yield,
                        time=time,
                        ingredients=ingredients,
                        username=username)
        db.session.add(recipe)
        db.session.commit()

        flash('Recipe added', "success")
        return redirect(f"/users/{username}")
    return render_template("new_recipe.html", form=form)
Exemplo n.º 3
0
def create_task():
    """Create a new recipe to db collection"""
    if 'logged_in' not in session:  # Check if its a logged in user
        flash(
            'Sorry, only logged in users can create recipes. Please register/login',
            'info')
        return redirect(url_for('index'))

    form = RecipeForm(request.form)  # Initialise the form
    user = mongo.db.user.find_one({"name": session['username'].title()})

    if form.validate_on_submit():  # Insert new recipe if form is submitted
        tasks = mongo.db.tasks
        tasks.insert_one({
            'recipe_name': request.form['recipe_name'],
            'recipe_image': request.form['recipe_image'],
            'ingredients': request.form['ingredients'],
            'serving_size': request.form['serving_size'],
            'recipe_course': request.form['recipe_course'],
            'allergen': request.form['allergen'],
            'calories': request.form['calories'],
            'description': request.form['description'],
            'cooking_time': request.form['cooking_time'],
            'instruction': request.form['instruction'],
            'instruction1': request.form['instruction1'],
            'instruction2': request.form['instruction2'],
            'instruction3': request.form['instruction3'],
            'instruction4': request.form['instruction4'],
            'instruction5': request.form['instruction5'],
            'instruction6': request.form['instruction6'],
            'username': session['username'].title(),
        })
        flash('Your Recipe has been added successfully', 'success')
        return redirect(url_for('index'))
    return render_template('add_recipe.html', form=form, title="Add Recipe")
Exemplo n.º 4
0
def index():
  recipe_form = RecipeForm(csrf_enabled=False)
  if recipe_form.validate_on_submit():
    new_id = len(recipes)+1
    recipes[new_id] = recipe_form.recipe.data
    types[new_id] = recipe_form.recipe_type.data
    descriptions[new_id] = recipe_form.description.data
    new_igredients = recipe_form.ingredients.data
    new_instructions = recipe_form.instructions.data
    add_ingredients(new_id, new_igredients)
    add_instructions(new_id, new_instructions)
    "I'm not sure why Codecademy added the following line for the '/' route, when comments aren't utilized"
    #comments[new_id] = []

    """
    When the new recipe is added, the browswe redirects to the newly added recipe's page
    """
    
    return redirect(
      url_for(
        "recipe",
        id = new_id,
        _external = True,
        _scheme="https"
      )
    )

  return render_template("index.html", template_recipes=recipes, template_form=recipe_form)
Exemplo n.º 5
0
def new_recipe():
    form = RecipeForm()
    if form.validate_on_submit():
        recipe = Recipes(name=form.name.data,note=form.description.data, category=form.category.data, subcategory=form.subcategory.data, food_type=form.cuisine.data,prep_time=form.prep_time.data,favourite=form.favourite.data)
        db.session.add(recipe)        
        db.session.flush()
        for p in form.photos.entries:
            photo = Photos.query.filter_by(filename=p.data).first()
            if photo:
                recipe.recipephotos.append(photo)
                db.session.add(recipe)
                db.session.flush()
            
        for i in form.ingridients.entries:
            i_list = IngidientList(recipe_id=recipe.id,quantity = i.data['quantity'], unit = i.data['unit'], ingridient_id=i.data['name'].id)
            db.session.add(i_list)
            db.session.flush()
            
        for idx, s in enumerate(form.steps.entries):
            s_name = "Step-"+str(idx+1)
            s_list = Steps(description = s.data['description'], recipe_id=recipe.id, name=s_name)
            db.session.add(s_list)
            db.session.flush()
            
            photo = Photos.query.filter_by(filename=s.data['photo']).first()
            if photo:
                s_list.photo_id = photo.id
        db.session.commit()
        flash('Recipe added successfully!','alert-success')
        return redirect(url_for('recipeapp.new_recipe'))
    if form.errors:
        flash(form.errors,'alert-danger')
    return render_template('recipeapp/editor.html',form=form)
Exemplo n.º 6
0
def edit_recipe(id):
    """ function that allows users to edit a recipe they
        have already posted to the database """

    chosen_recipe = mongo.db.recipes.find_one({'_id': ObjectId(id)})
    form = RecipeForm(data=chosen_recipe)

    if request.method == "GET":
        return render_template('edit_recipe.html',
                               form=form,
                               title="Edit Recipe")
    elif request.method == "POST":
        if form.validate_on_submit():
            recipes = mongo.db.recipes

            recipes.update_one({'_id': ObjectId(id)}, {
                '$set': {
                    'recipe_name': request.form['recipe_name'],
                    'summary': request.form['summary'],
                    'description': request.form['description'],
                    'ingredients': request.form['ingredients'],
                    'equipment': request.form['equipment'],
                    'prep_time': request.form['prep_time'],
                    'cook_time': request.form['cook_time'],
                    'serves_num': request.form['serves_num'],
                    'method': request.form['method'],
                    'course': request.form['course'],
                    'cuisine': request.form['cuisine'],
                }
            })
            flash('Recipe Updated ', 'success')
            return redirect(url_for('recipe', id=id))
    else:
        flash('An error occured', 'danger')
        return render_template('index.html')
Exemplo n.º 7
0
def edit_recipe(id=1):
    recipe = Recipe.query.filter_by(id = id).first()
    app.logger.info('Editing Recipe ' + str(id))
    form = RecipeForm(obj = recipe)
    if recipe == None:
        flash('Recipe not found.')
        return redirect(url_for('index'))
    if request.method == 'POST':
        app.logger.debug('request.data')
        app.logger.debug(request.data)
        app.logger.debug('Method = POST')
        valid = form.validate_on_submit()
        if valid:
            app.logger.info('Validation Successful - ' + str(form.recipe_name.data))
            form.populate_obj(recipe)
            if len(request.files) > 0 and request.files['image_file'].filename:
                req = request
                filename = req.files['image_file'].filename
                recipe_name = recipe.recipe_name
                recipe.image_path = upload_image(req, filename, recipe_name)
                if recipe.image_path is None:
                    app.logger.error('Error uploading image')
                    flash("Error uploading image")
                
            db.session.add(recipe)
            db.session.commit()
            flash('Your changes have been saved.')
            return redirect(url_for('view_recipe', id=id))
        else:
            app.logger.info("Failed Validation")
            
    return render_template('recipe_form.html',
        title="Edit a Recipe",
        form = form)
Exemplo n.º 8
0
def create_recipe():
    """Create a new recipe to db collection"""
    if 'logged_in' not in session:  # Check if its a logged in user
        flash('Sorry, only logged in users can create recipes.')
        return redirect(url_for('index'))

    form = RecipeForm(request.form)  # Initialise the form
    user = mongo.db.user.find_one({"name": session['username'].title()})

    if form.validate_on_submit():  # Insert new recipe if form is submitted
        recipes = mongo.db.recipe
        recipes.insert_one({
            'recipe': request.form['recipe_name'],
            'recipe_name': request.form['recipe_name'],
            'recipe_image': request.form['recipe_image'],
            'serving_size': int(request.form['serving_size']),
            'diet_labels': request.form['diet_labels'],
            'health_labels': request.form['health_labels'],
            'ingredients': request.form['ingredients'],
            'calories': request.form['calories'],
            'cooking_time': request.form['cooking_time'],
            'i-made-it': int(0),
            'description': request.form['description'],
            'source': request.form['source'],
            'username': session['username'].title(),
            'created_by': {
                '_id': user['_id'],
                'name': user['name']
            }
        })
        flash('Recipe Added!')
        return redirect(url_for('index'))
    return render_template('add_recipe.html', form=form, title="Add Recipe")
Exemplo n.º 9
0
def edit_task(task_id):
    count_tasks = mongo.db.tasks.find().count()
    favourite_count = mongo.db.tasks.find({'favourite': True}).count()
    if 'logged_in' not in session:  # Check if its a logged in user
        flash('Apologies, only logged in users can edit recipes.')
        return redirect(url_for('index'))

    user = mongo.db.user.find_one({"name": session['username'].title()})
    task = mongo.db.tasks.find_one_or_404({"_id": ObjectId(task_id)})
    form = RecipeForm()
    """
    Find a particular task, parameter passed is 'id', looking
    for a match to 'id' in MongoDB, then wrapped for editing
    purposes.
    Reuse much of the layout in 'add_tasks' function,
    but with pre-populated fields.
    """
    if user['name'].title() == task['username'].title():
        if request.method == 'GET':
            form = RecipeForm(data=task)
            current_user = mongo.db.user.find_one(
                {'name': session['username'].title()})
            return render_template('editrecipe.html',
                                   task=task,
                                   current_user=current_user,
                                   count_tasks=count_tasks,
                                   favourite_count=favourite_count,
                                   form=form,
                                   title="Edit Recipe")
        if form.validate_on_submit():
            tasks = mongo.db.tasks  # Access to the tasks collection in mongo.db
            tasks.update_one({
                '_id': ObjectId(task_id),
            }, {
                '$set': {
                    'category_name': request.form['category_name'],
                    'complexity': request.form['complexity'],
                    'recipe_name': request.form['recipe_name'],
                    'author_name': request.form['author_name'],
                    'prep_time_mins': int(request.form['prep_time_mins']),
                    'cook_time_mins': int(request.form['cook_time_mins']),
                    'calories': int(request.form['calories']),
                    'servings': int(request.form['servings']),
                    'brief_description': request.form['brief_description'],
                    'ingredients': request.form['ingredients'],
                    'instructions': request.form['instructions'],
                    'recipe_image': request.form['recipe_image'],
                    'favourite': 'favourite' in request.form
                }
            })
            flash('Your recipe has been updated!')
            return redirect(url_for('task', tasks_id=task_id))
    flash("Apologies, this is not your recipe to edit!")
    return redirect(url_for('task', tasks_id=task_id))
Exemplo n.º 10
0
def add_tasks():
    """
    Add a new recipe to mongodb database collection
    """
    count_tasks = mongo.db.tasks.find().count()
    favourite_count = mongo.db.tasks.find({'favourite': True}).count()
    # Allows task categories in MongoDB to connect with addtask.html file
    if 'logged_in' not in session:  # Check for user logged in
        flash('Apologies, only logged in users can add recipes.')
        return redirect(url_for('index'))

    form = RecipeForm(request.form)  # Initialise the form
    user = mongo.db.user.find_one({"name": session['username'].title()})
    if 'logged_in' in session:
        form = RecipeForm(request.form)
        current_user = mongo.db.user.find_one(
            {'name': session['username'].title()})
    else:
        return render_template('addrecipe.html',
                               count_tasks=count_tasks,
                               favourite_count=favourite_count,
                               page_title='Add New Recipe',
                               form=form,
                               current_user=current_user)
    if form.validate_on_submit():  # Insert new recipe if form is submitted
        tasks = mongo.db.tasks
        tasks.insert_one({
            'category_name': request.form['category_name'],
            'complexity': request.form['complexity'],
            'recipe_name': request.form['recipe_name'],
            'author_name': request.form['author_name'],
            'prep_time_mins': int(request.form['prep_time_mins']),
            'cook_time_mins': int(request.form['cook_time_mins']),
            'calories': int(request.form['calories']),
            'servings': int(request.form['servings']),
            'brief_description': request.form['brief_description'],
            'ingredients': request.form['ingredients'],
            'instructions': request.form['instructions'],
            'recipe_image': request.form['recipe_image'],
            'favourite': 'favourite' in request.form,
            'username': session['username'].title(),
            'created_by': {
                '_id': user['_id'],
                'name': user['name']
            }
        })
        return redirect(url_for('index'))
    return render_template('addrecipe.html',
                           count_tasks=count_tasks,
                           favourite_count=favourite_count,
                           current_user=current_user,
                           form=form,
                           title="Add New Recipe")
Exemplo n.º 11
0
def update_task(task_id):
    # Check if user is logged in
    if 'logged_in' not in session:  # Check if its a logged in user
        flash(
            'Sorry, only logged in users can edit their own recipes. Please login',
            'info')
        return redirect(url_for('index'))

    user = mongo.db.user.find_one({"name": session['username'].title()})
    the_task = mongo.db.tasks.find_one_or_404({'_id': ObjectId(task_id)})
    form = RecipeForm()

    # If user created then they can edit
    if user['name'].title() == the_task['username'].title():

        if request.method == 'GET':
            form = RecipeForm(data=the_task)
            return render_template('edit_recipe.html',
                                   task=the_task,
                                   form=form,
                                   title='Edit Recipe')

        if form.validate_on_submit():
            task = mongo.db.tasks
            task.update_one({
                '_id': ObjectId(task_id),
            }, {
                '$set': {
                    'recipe_name': request.form['recipe_name'],
                    'recipe_image': request.form['recipe_image'],
                    'ingredients': request.form['ingredients'],
                    'serving_size': request.form['serving_size'],
                    'recipe_course': request.form['recipe_course'],
                    'allergen': request.form['allergen'],
                    'calories': request.form['calories'],
                    'description': request.form['description'],
                    'cooking_time': request.form['cooking_time'],
                    'instruction': request.form['instruction'],
                    'instruction1': request.form['instruction1'],
                    'instruction2': request.form['instruction2'],
                    'instruction3': request.form['instruction3'],
                    'instruction4': request.form['instruction4'],
                    'instruction5': request.form['instruction5'],
                    'instruction6': request.form['instruction6'],
                }
            })
            flash('Your Recipe has been updated', 'info')
            return redirect(url_for('task', task_id=task_id))
    flash('Sorry not your recipe to edit!', 'danger')
    return redirect(url_for('task', task_id=task_id))
def index():
    recipe_form = RecipeForm(csrf_enabled=False)
    if recipe_form.validate_on_submit():
        new_id = len(recipes) + 1
        recipes[new_id] = recipe_form.recipe.data
        types[new_id] = recipe_form.recipe_type.data
        descriptions[new_id] = recipe_form.description.data
        new_ingredients = recipe_form.ingredients.data
        new_instructions = recipe_form.instructions.data
        add_ingredients(new_id, new_ingredients)
        add_instructions(new_id, new_instructions)
        comments[new_id] = []
    return render_template("index.html",
                           template_recipes=recipes,
                           template_form=recipe_form)
Exemplo n.º 13
0
def new_recipe():
    
    class IngredientSelector(Form):
        ingredients = models.Ingredient.query.order_by(models.Ingredient.name.asc())
        choices = []
        for each in ingredients:
            choices.append((str(each.id), each.name.title()))

        ingredient = SelectMultipleField(u'Ingredients', choices = choices)

    form = RecipeForm()
    selector = IngredientSelector()
    rid = models.Recipe
    if form.validate_on_submit():
        recipe = models.Recipe(
                name = form.name.data,
                difficulty = form.difficulty.data,
                time = form.time.data,
                servings = form.servings.data,
                instructions = form.instructions.data,
                user_id = g.user.get_id(),
                image = form.image.data
        )
        if form.image:
            form.image.data.save(os.path.join(RECIPE_IMAGE_PATH, '%s.jpg' % recipe.name))
            recipe.image = "/uploads/recipe_images/%s.jpg"% recipe.name
        if Recipe.query.filter_by(name = recipe.name).count() > 0:
            flash('A recipe with this name already exists!');
            return render_template('new_recipe.html', form = form, selector = selector)
        db.session.add(recipe)
        db.session.commit()
        
        selected_ingredients = selector.ingredient.data

        for each in selected_ingredients:
            i = Ingredient.query.get(each)
            recipe.add_ingredient(i)

        db.session.commit()

        flash(recipe.name + ' created!')
        return redirect(url_for('user', email = g.user.email))
    
    if form.errors:
        flash('A field in the recipe form was invalid!')
    
    return render_template('new_recipe.html', form = form, selector = selector)
Exemplo n.º 14
0
def get_recipes():
    form = RecipeForm()
    if form.validate_on_submit():
        name = form.name.data
        contents = [
            r.ingredient_name
            for r in db.session.query(MenuDish.ingredient_name).filter_by(
                dish_name=name).distinct()
        ]
        if not contents:
            flash("That item is not in the inventory!")
            return render_template('recipes.html', form=form)
        results = f"{name}"
        return render_template('recipe_results.html',
                               contents=contents,
                               results=results)
    return render_template('recipes.html', form=form)
Exemplo n.º 15
0
def index():
    recipe_form = RecipeForm()
    if recipe_form.validate_on_submit():
        new_id = len(recipes) + 1
        recipes[new_id] = recipe_form.recipe.data
        types[new_id] = recipe_form.recipe_type.data
        descriptions[new_id] = recipe_form.description.data
        new_ingredients = recipe_form.ingredients.data
        new_instructions = recipe_form.instructions.data
        add_ingredients(new_id, new_ingredients)
        add_instructions(new_id, new_instructions)
        comments[new_id] = []
        #### Redirect to recipe route here
        return redirect(url_for('recipe', id=new_id))
    return render_template("index.html",
                           template_recipes=recipes,
                           template_form=recipe_form)
Exemplo n.º 16
0
def index():
    recipe_form = RecipeForm(csrf_enabled=False)
    if recipe_form.validate_on_submit():
        new_id = len(recipes) + 1
        recipes[new_id] = recipe_form.recipe.data
        types[new_id] = recipe_form.recipe_type.data
        descriptions[new_id] = recipe_form.description.data
        new_igredients = recipe_form.ingredients.data
        new_instructions = recipe_form.instructions.data
        add_ingredients(new_id, new_igredients)
        add_instructions(new_id, new_instructions)
        comments[new_id] = []
        return redirect(
            url_for("recipe", id=new_id, _external=True, _scheme='https'))
    return render_template("index.html",
                           template_recipes=recipes,
                           template_form=recipe_form)
Exemplo n.º 17
0
def index():
    recipe_form = RecipeForm(request.form, meta={'csrf': False})
    if recipe_form.validate_on_submit():
        new_id = len(recipes) + 1
        recipes[new_id] = recipe_form.recipe.data
        types[new_id] = recipe_form.recipe_type.data
        descriptions[new_id] = recipe_form.description.data
        new_igredients = recipe_form.ingredients.data
        new_instructions = recipe_form.instructions.data
        add_ingredients(new_id, new_igredients)
        add_instructions(new_id, new_instructions)
        comments[new_id] = []
        #### Redirect to recipe route here
        return redirect(
            url_for("recipe", id=new_id, _external=True, _scheme='http'))
    return render_template("index.html",
                           template_recipes=recipes,
                           template_form=recipe_form)
Exemplo n.º 18
0
def add_recipe():
    """ function that allows user to create a new recipe
        and store it in the database """

    form = RecipeForm()

    # If they are trying to add a recipe and the form validates
    if request.method == "POST":
        if form.validate_on_submit():
            # Using base64 to store photo in database
            code_str = base64.b64encode(form.photo.data.read()).decode("utf-8")

            recipes = mongo.db.recipes
            # Add the recipe and tell the user it's added
            recipes.insert_one({
                'recipe_name': request.form['recipe_name'],
                'summary': request.form['summary'],
                'description': request.form['description'],
                'photo': "data:image/png;base64," + code_str,
                'ingredients': request.form['ingredients'],
                'equipment': request.form['equipment'],
                'prep_time': request.form['prep_time'],
                'cook_time': request.form['cook_time'],
                'serves_num': request.form['serves_num'],
                'method': request.form['method'],
                'course': request.form['course'],
                'cuisine': request.form['cuisine'],
                'username': session['username'],
            })
            flash('Recipe added', 'success')
            return redirect(url_for('user_profile'))
        else:
            flash('Please make sure form is filled out correctly', 'danger')
            return redirect(url_for('add_recipe'))
    elif request.method == "GET":
        return render_template('add_recipe.html',
                               form=form,
                               title='Add Recipe')
    else:
        flash('An error occured', 'danger')
        return render_template('index.html')
Exemplo n.º 19
0
def addrecipe():
    if 'username' not in session:
        flash('Not possible for non-members! Please create an account.')
        return redirect(url_for('register'))

    form = RecipeForm()
    if request.method == 'POST' and form.validate_on_submit():
        recipe = mongo.db.Recipes
        recipe.insert({'recipe_name': request.form['recipe_name'],
                       'recipe_type': request.form['recipe_type'],
                       'recipe_desc': request.form['recipe_desc'],
                       'serving': request.form['serving'],
                       'prep_time': request.form['prep_time'],
                       'cook_time': request.form['cook_time'],
                       'ingredients': request.form.getlist('ingredients'),
                       'method': request.form.getlist('methods'),
                       # Lists for Ingredients and Method to store in an array.
                       'img_url': request.form['img_url']})
        flash('Recipe successfully added.')
        return redirect(url_for('index'))
    return render_template('addrecipe.html', form=form)
Exemplo n.º 20
0
def recipe():
    form = RecipeForm()
    if form.validate_on_submit():

        #retrieve proportion data from form. 1 if (optionally) empty
        amount1 = (int(form.word1.data != "")
                   if form.amount1.data == None else form.amount1.data)
        amount2 = (int(form.word2.data != "")
                   if form.amount2.data == None else form.amount2.data)
        amount3 = (int(form.word3.data != "")
                   if form.amount3.data == None else form.amount3.data)
        amounts = [amount1, amount2, amount3]

        #retrieve word data from form. ""->" " if (optionally) empty
        word1 = (" "
                 if form.word1.data == "" else form.word1.data.strip().lower())
        word2 = (" "
                 if form.word2.data == "" else form.word2.data.strip().lower())
        word3 = (" "
                 if form.word3.data == "" else form.word3.data.strip().lower())
        words = [word1, word2, word3]

        #format and flash the input
        amount1 = int(amount1) if isinstance(
            amount1, float) and amount1.is_integer() else amount1
        amount2 = int(amount2) if isinstance(
            amount2, float) and amount2.is_integer() else amount2
        amount3 = int(amount3) if isinstance(
            amount3, float) and amount3.is_integer() else amount3
        flash(
            '{} {}{:+} {}{:+} {} ~'.format(amount1, word1, amount2, word2,
                                           amount3, word3), 'input')

        #look up synonyms from vector sum
        result = nearest_words(amounts, words)
        for word in result:
            flash(word, 'output')

        return redirect('/')
    return render_template('recipe.html', title='word+chef', form=form)
Exemplo n.º 21
0
def edit_recipe(recipe_id):
    """Function to edit selected recipe"""
    if 'logged_in' not in session:  # Check if its a logged in user
        flash('Sorry, only logged in users can create recipes.')
        return redirect(url_for('index'))

    user = mongo.db.user.find_one({"name": session['username'].title()})
    the_recipe = mongo.db.recipe.find_one_or_404({'_id': ObjectId(recipe_id)})
    form = RecipeForm()

    if user['name'].title() == the_recipe['username'].title():
        if request.method == 'GET':
            form = RecipeForm(data=the_recipe)
            return render_template('edit_recipe.html',
                                   recipe=the_recipe,
                                   form=form,
                                   title="Edit Recipe")
        if form.validate_on_submit():
            recipe = mongo.db.recipe
            recipe.update_one({
                '_id': ObjectId(recipe_id),
            }, {
                '$set': {
                    'recipe': request.form['recipe_name'],
                    'recipe_name': request.form['recipe_name'],
                    'recipe_image': request.form['recipe_image'],
                    'serving_size': int(request.form['serving_size']),
                    'diet_labels': request.form['diet_labels'],
                    'health_labels': request.form['health_labels'],
                    'ingredients': request.form['ingredients'],
                    'calories': request.form['calories'],
                    'cooking_time': request.form['cooking_time'],
                    'description': request.form['description'],
                    'source': request.form['source']
                }
            })
            flash('Recipe updated.')
            return redirect(url_for('recipe', recipe_id=recipe_id))
    flash("Sorry this is not your recipe to edit!")
    return redirect(url_for('recipe', recipe_id=recipe_id))
Exemplo n.º 22
0
def add_recipe(username):
  user = User.query.filter_by(username=username).first()
  form = RecipeForm()
  if form.validate_on_submit():
    name = request.form['name'];
    image = request.form['recipe_image']
    ingredients = request.form['ingredients'].splitlines()
    response = Macro_Api_Caller.get_Data(Macro_Api_Caller, name, ingredients)
    if 'error' in response:
      flash("Ingredients not valid, make sure ingredients are on separate lines.", "danger")
      return redirect(f"/users/{session['username']}/recipes/add")
    else:
      recipe = Recipe_Factory.process_Recipe(name, image, user, response)
      db.session.add(recipe)
      db.session.commit()
      add_Ingredients = [Ingredient(amount=ingredient, recipe_id=recipe.id) for ingredient in ingredients]
      db.session.add_all(add_Ingredients)
      db.session.commit()
      flash("Recipe added successfully!", "success")
      return redirect(f"/users/{user.username}/recipes")
  else: 
    return render_template("/recipes/add_recipe.html", form=form, user=user)
Exemplo n.º 23
0
def editRecipe(cuisine_id, recipe_id):
    """Edit Recipe page route"""
    # Redirects to the login page if the user is not logged in
    if 'username' not in login_session:
        return redirect('/login')

    # Fetches the recipe to edit it
    cuisine = session.query(Cuisine).filter_by(id=cuisine_id).one()
    editedRecipe = session.query(Recipe).filter_by(id=recipe_id).one()

    # Checking authorization of the user
    if editedRecipe.user_id != login_session['user_id']:
        return """<script>function myFunction() {
        msg = 'You are not authorized to edit this Recipe. ';
        msg += 'Please create your own Recipe in order to edit.';
        alert(msg);
        window.location.replace('""" + (url_for('showRecipes',
                                                cuisine_id=cuisine.id)) + """')
         ;}</script>
         <body onload='myFunction()'>"""
    # Creates the recipe form
    form = RecipeForm()
    # POST method functionality
    if request.method == 'POST':
        # Checks if all the fields are valid
        if form.validate_on_submit():
            # Updates the recipe and commits changes
            editedRecipe.name = form.name.data
            editedRecipe.description = form.description.data
            flash('Recipe Successfully Edited to %s' % editedRecipe.name)
            return redirect(
                url_for('showRecipe',
                        cuisine_id=cuisine_id,
                        recipe_id=editedRecipe.id))
    return render_template('editRecipe.html',
                           form=form,
                           cuisine=cuisine,
                           recipe=editedRecipe)
Exemplo n.º 24
0
def recipe_new():
    """Create a new recipe."""
    form = RecipeForm()
    LOGGER.debug("New recipe form.")
    if form.validate_on_submit():
        LOGGER.debug("Validating new recipe form.")
        recipe = Recipe(
            cook_time=form.cook_time.data,
            description=form.description.data,
            name=form.name.data,
            prep_time=form.prep_time.data,
            servings=form.servings.data,
            intro=form.intro.data,
        )
        session = db.session
        session.add(recipe)
        session.commit()
        LOGGER.info("Created recipe %s", form.name.data)
        return redirect(url_for('recipe', id=recipe.id))
    else:
        for error in form.errors:
            LOGGER.debug("Error: %s", error)

    return render_template('recipe_new.html', form=form)
Exemplo n.º 25
0
def newRecipe(cuisine_id):
    """New Recipe page route"""
    # Redirects to the login page if the user is not logged in
    if 'username' not in login_session:
        return redirect('/login')
    # Fetches the cuisine to which the recipe belongs to
    cuisine = session.query(Cuisine).filter_by(id=cuisine_id).one()

    # Creates the new recipe form
    form = RecipeForm()
    # POST method functionality
    if request.method == 'POST':
        # Checks if all the fields are valid
        if form.validate_on_submit():
            # Creates the new recipe and commits the changes
            newRecipe = Recipe(name=form.name.data,
                               description=form.description.data,
                               cuisine_id=cuisine_id,
                               user_id=login_session['user_id'])
            session.add(newRecipe)
            session.commit()
            flash('New Recipe %s Successfully Created' % (newRecipe.name))
            return redirect(url_for('showRecipes', cuisine_id=cuisine_id))
    return render_template('newRecipe.html', form=form, cuisine=cuisine)
Exemplo n.º 26
0
def addRecipe():
    form = RecipeForm()

    ingredient = get_ingredients()

    for row in ingredient:
        ing = row['ingredients_name']
        ingid = row['ingredients_id']
        ingu = row['measuring_unit']
        form.ingredient1.choices += [(ingid, ing + " - " + ingu)]
        form.ingredient2.choices += [(ingid, ing + " - " + ingu)]
        form.ingredient3.choices += [(ingid, ing + " - " + ingu)]
        form.ingredient4.choices += [(ingid, ing + " - " + ingu)]
        form.ingredient5.choices += [(ingid, ing + " - " + ingu)]
    if request.method == "POST" and form.validate_on_submit():
        now = datetime.datetime.now()
        recipename = form.name.data
        recipetype = form.recipetype.data
        diet_type = form.diet_type.data
        serving = form.serving.data
        preptime = form.preptime.data
        time_unit = form.time.data
        caloriecount = form.caloriecount.data
        unit1 = form.unit1.data
        ingredient1 = form.ingredient1.data
        unit2 = form.unit2.data
        ingredient2 = form.ingredient2.data
        unit3 = form.unit3.data
        ingredient3 = form.ingredient3.data
        unit4 = form.unit4.data
        ingredient4 = form.ingredient4.data
        unit5 = form.unit5.data
        ingredient5 = form.ingredient5.data
        instruction1 = form.instruction1.data
        instruction2 = form.instruction2.data
        instruction3 = form.instruction3.data
        instruction4 = form.instruction4.data
        instruction5 = form.instruction5.data
        f = form.upload.data
        filename = secure_filename(f.filename)
        username = session['user']
        cur = mysql.connection.cursor()
        cur.callproc("Recipe", [
            recipename, serving, preptime, time_unit, recipetype, diet_type,
            caloriecount, filename
        ])
        cur.close()
        mysql.connection.commit()  #Recipe Information is added to recipe table
        f.save(os.path.join(filefolder, filename))
        cur1 = mysql.connection.cursor()
        cur1.execute('SELECT MAX(recipe_id) AS id FROM recipes')
        maxid = list(cur1.fetchall())
        cur1.close()
        recipeid = maxid[0]['id']
        cur2 = mysql.connection.cursor()
        cur2.callproc("add_Recipe", [username, recipeid, now])
        cur2.close()
        mysql.connection.commit()
        cur3 = mysql.connection.cursor()
        cur3.callproc("Comprise", [recipeid, ingredient1, unit1])
        mysql.connection.commit()
        cur3.callproc("Comprise", [recipeid, ingredient2, unit2])
        mysql.connection.commit()
        cur3.callproc("Comprise", [recipeid, ingredient3, unit3])
        mysql.connection.commit()
        cur3.callproc("Comprise", [recipeid, ingredient4, unit4])
        mysql.connection.commit()
        cur3.callproc("Comprise", [recipeid, ingredient5, unit5])
        cur3.close()
        mysql.connection.commit()
        cur4 = mysql.connection.cursor()
        cur4.callproc("Instruction", [recipeid, instruction1])
        mysql.connection.commit()
        cur4.callproc("Instruction", [recipeid, instruction2])
        mysql.connection.commit()
        cur4.callproc("Instruction", [recipeid, instruction3])
        mysql.connection.commit()
        cur4.callproc("Instruction", [recipeid, instruction4])
        mysql.connection.commit()
        cur4.callproc("Instruction", [recipeid, instruction5])
        cur4.close()
        mysql.connection.commit()
        return redirect(url_for('profile'))
    return render_template("recipe.html", form=form)
Exemplo n.º 27
0
def recipes(recipe_id=None):
    if recipe_id == None:
        recipes = models.Recipe.select().limit(10)
        #recipes = models.Recipe.select().limit(10).where(models.Recipe.user_id == current_user.id)
        form = RecipeForm()

        recipeid = request.form.get('recipeid', '')
        command = request.form.get('submit', '')
        if command == 'Delete':
            models.Recipe.delete_by_id(recipeid)
            return redirect("/recipes")
        elif command == 'Edit':
            recipeid = int(recipeid)
            recipe = models.Recipe.get(models.Recipe.id == recipeid)
            form.id.data = recipe.id
            form.name.data = recipe.name
            form.image.data = recipe.image
            form.description.data = recipe.description
            form.ingredients.data = recipe.ingredients
            form.instructions.data = recipe.instructions

        if form.validate_on_submit():
            if form.id.data == '':
                models.Recipe.create(
                    name=form.name.data.strip(),
                    description=form.description.data.strip(),
                    ingredients=form.ingredients.data.strip(),
                    instructions=form.instructions.data.strip(),
                    image=form.image.data.strip(),
                    user_id=current_user.id)
                flash("New recipe created. Called: {}".format(form.name.data))
            else:
                recipe = models.Recipe.get(models.Recipe.id == form.id.data)
                recipe.name = form.name.data.strip()
                recipe.image = form.image.data.strip()
                recipe.description = form.description.data.strip()
                recipe.ingredients = form.ingredients.data.strip()
                recipe.instructions = form.instructions.data.strip()
                recipe.save()
                flash("recipe updated")
            return redirect('/recipes')
        return render_template("recipes.html",
                               recipes_template=recipes,
                               form=form)
    else:
        recipe_id = int(recipe_id)

        recipe = models.Recipe.get(models.Recipe.id == recipe_id)
        reviews_template = models.Review.select().where(
            models.Review.recipe_id == recipe_id)

        form = ReviewForm()
        reviews = models.Review.select().limit(10)
        reviewsid = request.form.get('reviewsid', '')
        command = request.form.get('submit', '')
        if command == 'Delete':
            models.Review.delete_by_id(reviewsid)
            return redirect('/recipes/{}'.format(recipe_id))

        elif command == 'Edit':
            reviewsid = int(reviewsid)
            review = models.Review.get(models.Review.id == reviewsid)
            form.id.data = review.id
            form.rating.data = review.rating
            form.comment.data = review.comment
            return render_template("review_form.html",
                                   recipe=recipe,
                                   form=form,
                                   reviews_template=reviews_template)
        if form.validate_on_submit():
            if form.id.data == '':
                models.Review.create(recipe_id=recipe_id,
                                     rating=form.rating.data,
                                     comment=form.comment.data.strip(),
                                     user_id=current_user.id)
            else:
                review = models.Review.get(models.Review.id == form.id.data)
                review.rating = form.rating.data
                review.comment = form.comment.data.strip()
                review.save()
                flash("review updated")
            return redirect('/recipes/{}'.format(recipe_id))
        else:
            return render_template("review_form.html",
                                   recipe=recipe,
                                   form=form,
                                   reviews_template=reviews_template)
Exemplo n.º 28
0
def create_recipe():
    form = RecipeForm()
    if form.validate_on_submit():

        return redirect("/recipes")
    return render_template("recipe-create.html", form=form)