Beispiel #1
0
def add_recipe_to_db():
    """Add selected recipe to recipes table in db."""

    pprint('in recipe_to_db route')
    # unencode from JSON
    data = request.get_json()
    recipe_details = data['recipe_details']
    recipe_id = recipe_details['recipe_id']
    pprint(recipe_details)
    # must log in to save a recipe
    if session.get('email') == None:
        return jsonify({'success': False, 'message': 'You need to create an account to save a recipe!'})

    # find if recipe already exists in db
    existing_recipe = crud.quick_get_recipe(recipe_id)

    if existing_recipe != None:
        print('\nrecipe already in db')
        return jsonify({'success': True, 'message': 'Recipe already in db, procdeed to saving'})

    print('\n new recipe, adding to db \n')
    title = recipe_details['title']
    image = recipe_details['image']
    servings = recipe_details['servings']
    sourceUrl = recipe_details['sourceUrl']
    cooking_mins = recipe_details['cooking_mins']
    prep_mins = recipe_details['prep_mins']
    ready_mins = recipe_details['ready_mins']
    # add recipe's title, image, and servings to recipes table in db
    crud.create_recipe(recipe_id=recipe_id, title=title, image=image, servings=servings, sourceUrl=sourceUrl, cooking_mins=cooking_mins, prep_mins=prep_mins, ready_mins=ready_mins)

    # add each individual ingredient of recipe to db.
    for ingredient in recipe_details['ingredients']:
        ingredient_id = ingredient['ingredient_id']
        name = ingredient['name']
        amount = ingredient['amount']
        unit = ingredient['unit']
        crud.add_recipe_ingredient(recipe=recipe_id, ingredient_id=ingredient_id, amount=amount, unit=unit, name=name)

    # add each instructions step and string to db
    for i, instruction in enumerate(recipe_details['instructions']):
        # set step_num by adding 1 to indices
        step_num = i + 1
        step_instruction = instruction
        crud.add_instructions(recipe=recipe_id, step_num=step_num, step_instruction=step_instruction)

    # add each key of equipment to db
    for equipment in recipe_details['equipment']:
        crud.add_equipment(recipe=recipe_id, equipment=equipment)

    return jsonify({'success': True, 'message': 'Recipe added to db!'})
Beispiel #2
0
def recipe_submitted():
    """User to upload their own recipe"""
    create_recipe_name = request.form.get('create_recipe_name')
    source_url = request.form.get('source-url')
    recipe_course = request.form.get('recipe-course')
    prep_time = request.form.get('prep-time')
    cook_time = request.form.get('cook-time')
    total_recipe_time = request.form.get('total-cook-time')
    ingredients = request.form.get('ingredients')
    recipe_description = request.form.get('recipe-description')
    servings = request.form.get('servings')
    directions = request.form.get('directions')
    filename = request.files.get('image-upload')
    if filename:
        response = cloudinary.uploader.upload(filename)
        print(response)
        image = response['secure_url']
    print(image)
    email = session['user']
    user = crud.get_user_by_email(email)
    user_id = user.user_id
    creating_recipe = crud.create_recipe(create_recipe_name, source_url,
                                         recipe_course, prep_time, cook_time,
                                         total_recipe_time, ingredients,
                                         recipe_description, servings,
                                         directions, image, user_id)

    return render_template('recipe_submitted.html',
                           creating_recipe=creating_recipe,
                           image=image)
Beispiel #3
0
def add_recipe_empty(user_cleanse_id):
    """Add a smoothie/recipe to a cleanse that does not have any smoothies/recipes"""

    if request.method == 'POST':

        timestamp = datetime.now()
        date = datetime.now()
        user_cleanse = crud.get_user_cleanse(user_cleanse_id)

        recipe_name = request.form.get('recipe_name')
        ingredient_name = request.form.get('ingredient_name')
        calories = request.form.get('calories')
        measurement = request.form.get('measurement')
        user = crud.get_user_by_email(session['email'])
        photo = "/static/img/smoothie.jpg"

        recipe = crud.create_recipe(recipe_name, user)
        ingredient = crud.create_ingredient(ingredient_name, calories,
                                            measurement, photo)

        crud.create_recipe_ingredient(recipe, ingredient)
        crud.create_user_cleanse_recipe(timestamp, date, user_cleanse, recipe)

        return redirect(f'/cleanse/{user_cleanse_id}')
    else:
        if 'user_id' not in session:
            return redirect('/login')

        return render_template('add_recipe.html')
Beispiel #4
0
def user_cleanse_recipes(user_cleanse_id):
    """Shows recipes/smoothies that belong to a specific cleanse and their ingredients
        Users can also submit an entry to their cleanse log for a specific cleanse"""

    if request.method == 'POST':
        if "form-submit" in request.form:
            timestamp = datetime.now()
            date = datetime.now()
            user_cleanse = crud.get_user_cleanse(user_cleanse_id)

            recipe_name = request.form.get('recipe_name')
            ingredient_name = request.form.get('ingredient_name')
            calories = request.form.get('calories')
            measurement = request.form.get('measurement')
            user = crud.get_user_by_email(session['email'])
            photo = "/static/img/smoothie.jpg"

            recipe = crud.create_recipe(recipe_name, user)
            ingredient = crud.create_ingredient(ingredient_name, calories,
                                                measurement, photo)

            crud.create_recipe_ingredient(recipe, ingredient)
            crud.create_user_cleanse_recipe(timestamp, date, user_cleanse,
                                            recipe)

            return redirect(f'/cleanse/{user_cleanse_id}')

        if "form2-submit" in request.form:
            timestamp = datetime.now()
            comment = request.form.get('comment')
            private = request.form.get('private')

            if private == 'on':
                private = False
            else:
                private = True

            user_cleanse = crud.get_user_cleanse(user_cleanse_id)
            crud.create_cleanse_log(timestamp, comment, private, user_cleanse)

            return redirect(f'/cleanse/{user_cleanse_id}')
    else:

        if 'user_id' not in session:
            return redirect('/login')

        user_cleanse = crud.get_user_cleanse(user_cleanse_id)
        user_cleanse_recipes = crud.get_user_cleanse_recipes(user_cleanse_id)
        session['user_cleanse_id'] = user_cleanse_id
        cleanse_logs = crud.get_cleanse_logs(user_cleanse_id)

        return render_template('cleanse_details.html',
                               user_cleanse_recipes=user_cleanse_recipes,
                               user_cleanse=user_cleanse,
                               cleanse_logs=cleanse_logs)
Beispiel #5
0
def seed_create_recipes():
    with open('data/recipes.json') as f:
        create_recipes = json.loads(f.read())

    for recipe in create_recipes:
        create_recipe_name = recipe['create_recipe_name']
        source_url = recipe['source_url']
        recipe_course = recipe['recipe_course']
        prep_time = recipe['prep_time']
        cook_time = recipe['cook_time']
        total_recipe_time = recipe['total_recipe_time']
        ingredients = recipe['ingredients']
        recipe_description = recipe['recipe_description']
        servings = recipe['servings']
        directions = recipe['directions']
        image = recipe['image']
        user_id = recipe['user_id']
        crud.create_recipe(create_recipe_name, source_url, recipe_course,
                           prep_time, cook_time, total_recipe_time,
                           ingredients, recipe_description, servings,
                           directions, image, user_id)
Beispiel #6
0
    def test_create_recipe(self):
        """Can we create recipe instance"""

        user3 = crud.create_user("*****@*****.**", "1234567", "Billy",
                                 "Corgan")
        folder3 = crud.create_folder(user3, "Pies")
        recipe3 = crud.create_recipe(folder3, "Apple Pie",
                                     "Apples, Crust, Sugar, Cinnamon",
                                     "Mix everything together",
                                     "http://google.com", "/static/pie.png")
        self.assertIsNotNone(recipe3.recipe_id)
        self.assertEqual(recipe3.recipe_title, "Apple Pie")
def create_recipe_card():
    # import pdb
    # pdb.set_trace()
    title = request.form.get("title")
    # print(title)
    cuisine = request.form.get("cuisine")
    instructions = request.form.get("instructions")
    servings = request.form.get("servings")

    ready_in_minutes = request.form.get("ready_in_minutes")
    image_cloud = request.files.get("image")

    # ingredients list manipulations
    ingredient_list = request.form.get("ingredients")
    # print(ingredient_list, type(ingredient_list))
    # print("list :" + ingredient_list)
    # print(type(ingredient_list))
    ingredients = ingredient_list.strip('][')  # to be stored in db
    # print("stored in db", ingredients, type(ingredients))
    ing_list = ingredient_list.strip('][').split(', ')  #to be rendered
    # print("rendering now", ing_list, type(ing_list))
    maybe = re.sub(r'["]', '', ingredients)
    # print("maybe is ", maybe, type(maybe))
    # maybe2 = maybe.split(', ')
    # print("maybe 2 ", maybe2, type(maybe2))

    if image_cloud:
        result = cloudinary.uploader.upload(image_cloud,
                                            api_key=CLOUDINARY_KEY,
                                            api_secret=CLOUDINARY_KEY_SECRET,
                                            cloud_name='dplmlgxqq')

        image = result['secure_url']
    else:
        image = None

    # print(request.json)

    # from user input get the cuisine_id
    # cuisine_id = crud.get_cuisine_id_from_name(cuisine)

    recipe = crud.create_recipe(title, servings, ready_in_minutes,
                                instructions, ingredients, cuisine, image)

    return render_template("create_recipe_card.html",
                           title=title,
                           cuisine=cuisine,
                           instructions=instructions,
                           servings=servings,
                           image=image,
                           ingredients=maybe,
                           ready_in_minutes=ready_in_minutes)
Beispiel #8
0
def create_recipe():
    """Show create recipe page."""

    if request.method == "GET":

        cuisines = crud.get_cuisines()
        categories = crud.get_categories()
        ingredients = crud.get_ingredients()

        if session.get("user_id") == None:
            flash("Please log in to create a new recipe.")
            return redirect('/')

        return render_template("create_recipe.html",
                               cuisines=cuisines,
                               categories=categories,
                               ingredients=ingredients)

    elif request.method == "POST":

        kwargs = {
            "title": request.form.get("title"),
            "description": request.form.get("description"),
            "prep_time": request.form.get("prep_time"),
            "cook_time": request.form.get("cook_time"),
            "total_time": request.form.get("total_time"),
            "serving_qty": request.form.get("serving_qty"),
            "source": request.form.get("source"),
            "user_id": session.get("user_id"),
            "cuisine_id": request.form.get("cuisine_id")
        }

        recipe = crud.create_recipe(**kwargs)

        category_id = request.form.get("category_id")
        crud.create_recipe_category(recipe.recipe_id, category_id)

        # Get ingredient, measurement, and instruction items in a dictionary
        # If flat is False, returns all items as a list
        request_dict = request.form.to_dict(flat=False)

        for ingredient, measurement in zip(request_dict["ingredients"],
                                           request_dict["measurements"]):
            ingredient_object = crud.create_ingredient(ingredient)
            crud.create_recipe_ingredient(recipe.recipe_id,
                                          ingredient_object.ingredient_id,
                                          measurement)

        for step_num, instruction in enumerate(request_dict["instructions"]):
            crud.create_recipe_step(recipe.recipe_id, step_num + 1,
                                    instruction)

        # Get images from create recipe form
        for image in request_dict["images"]:
            image_object = crud.create_image(image)
            crud.create_recipe_image(recipe.recipe_id, image_object.image_id)

        if recipe:
            flash('Congrats! A new recipe was created.')

        else:
            flash('Error.')

        return redirect('/create_recipe')
Beispiel #9
0
    calories_2 = SEED[i]['ingredients'][2]['calories']
    measurement_2 = SEED[i]['ingredients'][2]['measurement']
    photo_2 = SEED[i]['ingredients'][2]['photo']
    i_name_3 = SEED[i]['ingredients'][3]['name']
    calories_3 = SEED[i]['ingredients'][3]['calories']
    measurement_3 = SEED[i]['ingredients'][3]['measurement']
    photo_3 = SEED[i]['ingredients'][3]['photo']

    global_comment_dict = SEED[i].get('global_comments', {'comment': 'test'})
    global_comment = global_comment_dict['comment']
    comment_timestamp = global_comment_dict['timestamp']


    db_user = crud.create_user(username, email, hashed, name, location, about, member_since)
    db_ingredient = crud.create_ingredient(i_name, calories, measurement_1, photo_1)
    db_ingredient_2 = crud.create_ingredient(i_name_2, calories_2, measurement_2, photo_2)
    db_ingredient_3 = crud.create_ingredient(i_name_3, calories_3, measurement_3, photo_3)
    db_recipe = crud.create_recipe(r_name, db_user)
    db_cleanse = crud.create_cleanse(start_date, end_date, public, description, db_user)

    crud.create_recipe_ingredient(db_recipe, db_ingredient)
    crud.create_recipe_ingredient(db_recipe, db_ingredient_2)
    crud.create_recipe_ingredient(db_recipe, db_ingredient_3)

    db_user_cleanse = crud.create_user_cleanse(active, completed, db_cleanse, db_user)
    crud.create_user_cleanse_recipe(timestamp, start_date, db_user_cleanse, db_recipe)
    crud.create_cleanse_log(clog_timestamp, comment, private, db_user_cleanse)

    db_comment = crud.create_global_comment(global_comment, timestamp, db_user)

Beispiel #10
0
        current_folder = choice(folders_data['folders'])

        new_folder = crud.create_folder(new_user, current_folder)

        for rec in range(3):

            random_recipe = choice(recipes_data)

            recipe_title = random_recipe["recipe_title"]
            recipe_ingred = random_recipe["recipe_ingred"]
            recipe_direct = random_recipe["recipe_direct"]
            recipe_src = random_recipe["recipe_src"]
            picture_url = random_recipe["picture_url"]

            new_recipe = crud.create_recipe(new_folder, recipe_title,
                                            recipe_ingred, recipe_direct,
                                            recipe_src, picture_url)

        # for tg in range(3):

        #     tags = []

        #     random_tag = choice(tags_data["tag"])

        #     new_tag = crud.create_tag(new_user, random_tag)

        #     tags.append(new_tag)

        #     current_tag = crud.create_recipe_tag((choice(tags)), new_recipe)
Beispiel #11
0
def create_test_recipes(test_users):
    """Create test recipes."""

    test_recipes_in_db = []

    # Capture test recipes from get_test_recipes() function
    test_recipes = get_test_recipes()

    for test_recipe in test_recipes:
        user = choice(test_users)
        prep_time = randint(5, 20)
        cook_time = randint(10, 30)

        kwargs = {
            "title":
            test_recipe["strMeal"],
            "description":
            "Sample recipe from TheMealDB API",
            "prep_time":
            prep_time,
            "cook_time":
            cook_time,
            "total_time":
            prep_time + cook_time,
            "serving_qty":
            randint(1, 5),
            "source":
            "Sample recipe from TheMealDB API",
            "user_id":
            user.user_id,
            "cuisine_id":
            crud.get_cuisine_id_by_cuisine_name(test_recipe["strArea"])
        }

        recipe = crud.create_recipe(**kwargs)
        test_recipes_in_db.append(recipe)

        # Seed database with recipe step(s)
        crud.create_recipe_step(recipe.recipe_id, 1,
                                test_recipe["strInstructions"])

        # Seed database with recipe ingredients, measurements
        # Using create_test_recipe_ingredients() function
        create_test_recipe_ingredients(test_recipe, recipe.recipe_id)

        # Seed database with recipe category
        category = crud.get_category_by_name(test_recipe["strCategory"])
        crud.create_recipe_category(recipe.recipe_id, category.category_id)

        # Seed database with an image
        image = create_test_image(test_recipe)

        # Seed database with recipe image
        crud.create_recipe_image(recipe.recipe_id, image.image_id)

        # Generate random rating
        rating_value = randint(1, 5)

        # Seed database with rating
        crud.create_rating(rating_value, user.user_id, recipe.recipe_id)

    return test_recipes_in_db
Beispiel #12
0
## get series data from file
with open('data/series.json') as f:
    series_data = json.loads(f.read())

for entry in series_data:
    series = crud.create_series(entry['series_code'], entry['name'])

# seed recipes table
## get recipes data from file
with open('data/recipes.json') as f:
    recipes_data = json.loads(f.read())

for entry in recipes_data:
    series_code = entry.get('series_code', None)

    recipe = crud.create_recipe(entry['name'], entry['cat_code'], series_code)

# seed materials table
## get materials data from file
with open('data/materials.json') as f:
    mat_data = json.loads(f.read())

    for entry in mat_data:
        material = crud.create_material(entry['name'], entry['iscraftable'])

# seed recipe_materials table
## get recipematerials data from file
with open('data/recipematerials.json') as f:
    rcpmat_data = json.loads(f.read())

    for entry in rcpmat_data: