Exemple #1
0
def test_data(client):
    '''Test dataset with two recipes, used in all tests'''
    pasta = Recipe(name='Pasta', procedure='Start by...', time=30)
    pasta_ingredients = [
        Ingredient(recipe_id=pasta.id,
                   name='Pasta',
                   measurement='2',
                   measurement_unit='packs'),
        Ingredient(recipe_id=pasta.id,
                   name='Tomato Paste',
                   measurement='300',
                   measurement_unit='grams'),
        Ingredient(recipe_id=pasta.id,
                   name='Onion',
                   measurement='1',
                   measurement_unit='pcs'),
    ]
    pasta.ingredients = pasta_ingredients
    pasta.insert()

    omelette = Recipe(name='Omelette', procedure='Start by...', time=10)
    omelette_ingredients = [
        Ingredient(recipe_id=omelette.id,
                   name='Egg',
                   measurement='3',
                   measurement_unit='pcs'),
        Ingredient(recipe_id=omelette.id,
                   name='Pepper',
                   optional=True,
                   measurement='1',
                   measurement_unit='pinch')
    ]
    omelette.ingredients = omelette_ingredients
    omelette.insert()
Exemple #2
0
def add_recipe(recipe):
    """Add recipe to favorites tables in the DB"""
    id = recipe.get('id', None)
    title = recipe.get('title', None)
    image = recipe.get('image', None)
    sourceName = recipe.get('sourceName', None)
    sourceUrl = recipe.get('sourceUrl', None)
    readyInMinutes = recipe.get('readyInMinutes', None)
    servings = recipe.get('servings', None)

    favorite_recipe = Recipe(id=id,
                             title=title,
                             image=image,
                             sourceName=sourceName,
                             sourceUrl=sourceUrl,
                             readyInMinutes=readyInMinutes,
                             servings=servings)

    try:
        db.session.add(favorite_recipe)
        db.session.commit()

    except Exception:
        db.session.rollback()
        print("THIS IS AN EXCEPTION", str(Exception))
        return "ERROR OCCURED IN SAVING RECIPE, PLEASE TRY AGAIN", str(
            Exception)
    return favorite_recipe
Exemple #3
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)
Exemple #4
0
def addRecipe():
    """RESTful method for creating a recipe"""
    # Check if the token is correct to prevent CSRF
    if request.headers.get('italian-recipes-token') != login_session['state']:
        resp = jsonify(error=['You are not allowed to make such request.'])
        resp.status_code = 401
        return resp

    # Check if user is logged in
    if 'username' not in login_session:
        resp = jsonify(error=['You are not allowed to do this'])
        resp.status_code = 401
        return resp

    # Check if all require input fields were filled
    # Sanitize input data
    data = checkRecipeForm(request.get_json())
    # If no errors, we are good
    if (len(data.errors) == 0):
        newRecipe = Recipe(name=data.inputs['name'],
                           description=data.inputs['description'],
                           duration=data.inputs['duration'],
                           difficulty=data.inputs['difficulty'],
                           region_id=data.inputs['region_id'],
                           user_id=login_session['user_id'])
        db_session.add(newRecipe)
        db_session.commit()
        return jsonify(id=newRecipe.id, name=newRecipe.name)
    else:
        resp = jsonify(error=data.errors)
        resp.status_code = 400
        return resp
Exemple #5
0
def add_recipe_to_db(recipe_data):
    """Add a recipe to the db recipe_data (obj): recipe data from the Spoonacular API Returns the recipe from the db"""

    id = recipe_data.get('id', None)
    title = recipe_data.get('title', None)
    image = recipe_data.get('image', None)
    sourceName = recipe_data.get('sourceName', None)
    sourceUrl = recipe_data.get('sourceUrl', None)
    readyInMinutes = recipe_data.get('readyInMinutes', None)
    servings = recipe_data.get('servings', None)
    instructions = recipe_data.get('instructions', None)
    vegetarian = recipe_data.get('vegetarian', None)
    vegan = recipe_data.get('vegan', None)
    glutenFree = recipe_data.get('glutenFree', None)
    dairyFree = recipe_data.get('dairyFree', None)
    sustainable = recipe_data.get('sustainable', None)
    ketogenic = recipe_data.get('ketogenic', None)

    recipe = Recipe(id=id, title=title, image=image, sourceName=sourceName, sourceUrl=sourceUrl,
                    readyInMinutes=readyInMinutes, servings=servings, instructions=instructions, vegetarian=vegetarian, vegan=vegan, glutenFree=glutenFree, dairyFree=dairyFree, sustainable=sustainable, ketogenic=ketogenic)
    try:
        recipe = add_and_commit(recipe)
    except Exception:
        db.session.rollback()
        print(str(Exception))
        return "Recipe couldn't be saved. Please try again."

    ingredients = add_ingredients_to_db(recipe_data)
    for ingredient in ingredients:
        recipe.ingredients.append(ingredient)
        db.session.commit()

    return recipe
Exemple #6
0
    def setUp(self):
        """Create test client, add sample data."""

        db.drop_all()
        db.create_all()

        user1 = User.signup(username="******",
                            first_name="first1",
                            last_name="last1",
                            email="*****@*****.**",
                            password="******")
        user1.id = 1000
        user1_id = user1.id

        db.session.commit()

        new_recipe = Recipe(
            recipe_id=2000,
            title="Roast Chicken",
            image=
            "https://www.recipetineats.com/wp-content/uploads/2020/02/Honey-Garlic-Chicken-Breast_5-SQ.jpg"
        )
        db.session.add(new_recipe)
        db.session.commit()

        self.user1 = User.query.get(user1_id)
Exemple #7
0
def get_ingredients(name):
    recipe = Recipe(**mongo.get_db().recipe.find_one({"name": name}))
    ingredients = []
    # add all ingredient ids in a list
    for ingredient in recipe.ingredients:
        ingredients.append(ingredient)
    return ingredients
Exemple #8
0
async def is_cocktail_mixable(name: str):
    recipeExists = False
    # get all recipes and check if a recipe with this name exists
    recipes = []
    for recipe in mongo.get_db().recipe.find():
        recipes.append(Recipe(**recipe))
    for recipe in recipes:
        if recipe.name == name:
            recipeExists = True

    if recipeExists is False:
        raise HTTPException(status_code=404,
                            detail='Error: This Recipe does not exist')

    # check if cocktail is mixable
    mixable = False

    ingredient_ids = get_ingredient_ids(name)

    # check for every ingredient by its id if dispenser is not -1
    for ingredient_id in ingredient_ids:
        # if one dispenser value of an ingredient is -1 set mixable false and break the loop
        if mongo.get_db().ingredient.find({
                "$and": [{
                    "_id": ObjectId(ingredient_id)
                }, {
                    "dispenser": -1
                }]
        }).count() > 0:
            mixable = False
            break
        else:
            mixable = True
    return {'data': mixable}
Exemple #9
0
def newRecipe(spirit_id):
    if 'username' not in login_session:
        return redirect('/login')
    spirits = session.query(Spirit).order_by(asc(Spirit.name))
    spirit = session.query(Spirit).filter_by(id=spirit_id).one()
    recipes = session.query(Recipe).filter_by(spirit_id=spirit_id).all()
    if login_session['user_id'] != spirit.user_id:
        return """<script>function myFunction()
                  {alert('You are not authorized to add menu items to this
                   spirit. Please create your own spirit or recipe in order to
                   add items.');}</script><body onload='myFunction()'>"""
    if request.method == 'POST':
        newRecipe = Recipe(name=request.form['name'],
                           description=request.form['description'],
                           ingredients=request.form['ingredients'],
                           instructions=request.form['instructions'],
                           spirit_id=spirit_id,
                           user_id=spirit.user_id)
        session.add(newRecipe)
        session.commit()
        flash('New Menu %s Item Successfully Created' % (newRecipe.name))
        return redirect(
            url_for('showRecipes',
                    spirits=spirits,
                    recipes=recipes,
                    spirit=spirit,
                    spirit_id=spirit_id))
    else:
        return render_template('newRecipe.html',
                               spirits=spirits,
                               recipes=recipes,
                               spirit=spirit)
Exemple #10
0
    def setUp(self):
        """Create test client, add sample data."""

        db.drop_all()
        db.create_all()
        Receipe_Ingredient.query.delete()
        User_View_Receipe.query.delete()
        Recipe.query.delete()
        Ingredient.query.delete()
        User.query.delete()
        self.client = app.test_client()
        u = User(email="*****@*****.**",
                 username="******",
                 password="******")
        u.id = 5555
        db.session.add(u)
        db.session.commit()
        recipe = Recipe(name='Pasta and Seafood',
                        colories=320,
                        rating=4.5,
                        cost=34,
                        time_to_cook=120,
                        image='pasta.jpg')
        recipe.id = 1234
        db.session.add(recipe)
        db.session.commit()
Exemple #11
0
def addRecipe():
    res=input('Introduce: nombre " || " descripcion ,de la nueva receta\n')
    try:
        name, desc= res.split(' || ', maxsplit=1)
    except ValueError:
        print('Introduce una cadena separada por " || " sin comillas')
        return
    #conseguimos los materiales que conforman la receta
    listMaterials()
    res=input('Selecciona separando por "," los materiales de la receta\n \
    Ejemplo: azufre x 2, acido x 1, 2(<--tbn indexa por id) x 3\n  ')
    #lista de "punteros(nombres o ids) a los materiales"
    lMatPointers= res.split(',')
    #conseguimos los materiales
    lR_MAsocs=[]
    for pointer in lMatPointers:
            pointer,num=pointer.split(' x ')
            print(pointer,num)
            mat=getMaterial(pointer)
            lR_MAsocs.append(Re_MatAssociation(mat,num))


    r=Recipe(name, desc, lR_MAsocs)
    m=Material(name,desc)


    #añadimos la receta a la base de datos(no hasta el commit)
    session.add(m)
    session.add(r)
    try:
        session.commit()
    #es en el commit donde puede dar errores de integridad
    except IntegrityError:
        session.rollback()
        print('Ha habido un problema con la nueva receta')
Exemple #12
0
def insert_recipe(recipe, user):
    existing_recipe = recipe_by_name(recipe['name'])
    version = 0 
    if (existing_recipe):
        print("Recipe version:", existing_recipe.version)
        version = existing_recipe.version + 1
    
    recipe_model = Recipe(
        name=recipe['name'],
        userid=user.id,
        version=version,
        public=True,
        batchvolume=recipe['batchvolume'],
        batchnic=recipe['batchnic'],
        batchratio=recipe['batchratio'],
        basenic=recipe['basenic'],
        baseratio=recipe['baseratio'],
        flavours=[Flavour(name=x['label'], percentage=x['percentage']) for x in recipe["flavours"]]
    )

    if existing_recipe is not None:
        if recipe_model == existing_recipe:
            print("No difference between recipes - skipping insertion")
            return
    try:
        db.session.add(recipe_model)
        db.session.commit()
    except Exception as ex:
        print(ex)
Exemple #13
0
def add_recipe():
    """
    After user enters recipe information into forms in settings.html this
    function adds the recipe to the database
    :return: index.html
    """
    if request.method == "POST":
        user_recipe = Recipe(
            recipe_title=request.form.get("recipe_title"),
            recipe_date=datetime.utcnow(),
            recipe_description=request.form.get("recipe_description"),
            recipe_rating=5,
            recipe_picture=request.form.get("recipe_picture"),
            recipe_cooking_time=request.form.get("recipe_cooking_time"),
            recipe_calorie_count=request.form.get("recipe_calorie_count"),
            recipe_ingredients=None)
        current_user.recipes.append(user_recipe)
        db.session.add(user_recipe)

        # threading for sending socketIO event
        follower_ids = [
            follower.id for follower in user_recipe.recipe_author.followers
        ]
        thr = threading.Thread(target=handle_new_recipe,
                               args=(user_recipe, follower_ids))
        thr.daemon = True
        thr.start()

        db.session.commit()
    return render_template('index.html')
Exemple #14
0
def add_recipe():
    """save recipe to users recipes"""
    if "user_id" not in session:
        flash("Login First or sign for an ccount!", "primary")
        return redirect("/login")
    user_id = session["user_id"]
    recipe_id = request.form["recipe"]
    r = Recipe.query.filter(Recipe.user_id == user_id,
                            Recipe.recipe_id == recipe_id).first()
    if r is not None:
        flash("Already in your recipes", "warning")
        return redirect("/")
    try:
        recipe = Recipe(recipe_id=recipe_id, user_id=user_id)
        db.session.add(recipe)
        db.session.commit()
    except IntegrityError:
        flash("Already in your Recipes!")
    my_recipes = []
    recipes = Recipe.query.filter(Recipe.user_id == session["user_id"]).all()
    for recipe in recipes:
        url = "https://www.themealdb.com/api/json/v1/1/lookup.php?i="
        try:
            res = requests.get(f"{url}{recipe.recipe_id}", params={'key': KEY})
        except:
            flash("That recipe is no longer available", "warning")
        data = res.json()
        my_recipe = data["meals"]
        r = my_recipe[0]
        my_recipes.append(r)
    return render_template("recipes.html", my_recipes=my_recipes)
Exemple #15
0
def create_recipe():
    data = request.get_json()
    recipe = data.get("recipe")
    owner = data.get("owner")

    user = AppUser.query.filter(AppUser.name == owner).first()

    if user is None:
        user = AppUser(name=owner)
        try:
            user.insert()
        except:
            abort(422)

    title = recipe.get("recipeTitle")
    ingredients = json.dumps(recipe.get("ingredients", ""))
    instructions = recipe.get("instructions")
    recipe = Recipe(title=title, ingredients=ingredients, instructions=instructions, owner_id=user.id)

    try:
        recipe.insert()
    except:
        abort(422)

    return jsonify({
        "success": True,
        "recipe": recipe.long(),
    })
Exemple #16
0
def createRecipe():
    # GET route delivers a form to create a new recipe, seeding it with state
    # variable
    if request.method == 'GET':
        if 'username' not in login_session:
            return redirect(url_for('showLogin'))
        state = login_session['state']
        print(get_flashed_messages())
        return render_template('newrecipe.html',
                               username=login_session['username'],
                               STATE=login_session['state'])
    # POST route checks that state variable received from that form is
    # correct, creates recipe in database and redirects to create ingredient
    # page
    if request.method == 'POST':
        if request.form['state'] != login_session['state']:
            response = make_response(json.dumps('Invalid state parameter.'),
                                     401)
            response.headers['Content-Type'] = 'application/json'
            return response
        newRecipe = Recipe(name=request.form['name'],
                           description=request.form['description'],
                           difficulty=request.form['difficulty'],
                           cuisine_id=request.form['cuisine'],
                           user_id=getUserId(login_session['email']))
        session.add(newRecipe)
        session.commit()
        flash("recipe successfully created!")
        return redirect(
            url_for('create_ingredient',
                    cuisine_id=newRecipe.cuisine_id,
                    recipe_id=newRecipe.id))
Exemple #17
0
 def process_Recipe(name, image, user, response):
     """Converts data to whole numbers and returns Recipe model"""
     calories = round(response['calories']) if response['calories'] else 0
     carbs = round(response['totalNutrients']['CHOCDF']['quantity'])
     fat = round(response['totalNutrients']['FAT']['quantity'])
     protein = round(response['totalNutrients']['PROCNT']['quantity'])
     fiber = round(response['totalNutrients']['FIBTG']['quantity'])
     carbs_from = round(
         response['totalNutrientsKCal']['CHOCDF_KCAL']['quantity'])
     fat_from = round(
         response['totalNutrientsKCal']['FAT_KCAL']['quantity'])
     protein_from = round(
         response['totalNutrientsKCal']['PROCNT_KCAL']['quantity'])
     recipe_img = image or Recipe.recipe_image.default.arg
     return Recipe(name=name,
                   calories=calories,
                   recipe_image=recipe_img,
                   carbs=carbs,
                   fat=fat,
                   protein=protein,
                   fiber=fiber,
                   carbs_from=carbs_from,
                   protein_from=protein_from,
                   fat_from=fat_from,
                   user_id=user.id)
Exemple #18
0
def add_favorite_dish(dish_id):
    """add favorite dish"""

    if not g.user:
        flash("Access Denied Please Login First", "danger")
        return redirect("/login")

    if not Recipe.query.get(dish_id):
        response = requests.get(
            f"https://api.spoonacular.com/recipes/{dish_id}/information?&apiKey={API_SECRET_KEY}"
        )
        dish = response.json()
        new_recipe = Recipe(recipe_id=dish_id,
                            title=dish["title"],
                            image=dish["image"])
        db.session.add(new_recipe)
        db.session.commit()

    timestamp = datetime.utcnow()
    new_favorite = User_Favorite(user_id=g.user.id,
                                 timestamp=timestamp,
                                 recipe_id=dish_id)
    db.session.add(new_favorite)
    db.session.commit()

    return jsonify(message="Dish Favorited")
Exemple #19
0
async def get_recipe_by_name(name: str):
    req = mongo.get_db().recipe.find_one({"name": name})
    if req is None:
        raise HTTPException(status_code=404, detail="Error: Recipe not found")

    recipe = Recipe(**req)
    return {'data': recipe}
Exemple #20
0
def post_comment(dish_id):
    """post user comment"""
    if not g.user:
        flash("Access Denied Please Login First", "danger")
        return redirect("/login")

    comment = request.form["comment"]

    if not Recipe.query.get(dish_id):
        response = requests.get(
            f"https://api.spoonacular.com/recipes/{dish_id}/information?&apiKey={API_SECRET_KEY}"
        )
        dish = response.json()
        new_recipe = Recipe(recipe_id=dish_id,
                            title=dish["title"],
                            image=dish["image"])
        db.session.add(new_recipe)
        db.session.commit()

    timestamp = datetime.utcnow()
    new_comment = User_Comment(user_id=g.user.id,
                               timestamp=timestamp,
                               recipe_id=dish_id,
                               comment=comment)
    db.session.add(new_comment)
    db.session.commit()

    return redirect(f"/dish/{dish_id}")
Exemple #21
0
def getRecipe(data, ownerId):
    title = data[TITLE_ID]
    desc = data[DESCRIPTION_ID]
    calories = data[CALORIES_ID]
    video = data[VIDEO_ID]
    recipe = Recipe(ownerId, title, desc, calories, video)
    return recipe
Exemple #22
0
    def test_message_model(self):
        """Does basic model work?"""

        m = Recipe(id=123456)

        db.session.add(m)
        db.session.commit()
Exemple #23
0
    def setUp(self):
        """create test client, and add sample data"""

        User.query.delete()
        Cabinet.query.delete()
        Recipe.query.delete()
        Follows.query.delete()
        Favorites.query.delete()
        Comment.query.delete()
        Post.query.delete()
        Ingredient.query.delete()
        db.session.commit()

        self.client = app.test_client()

        self.u = User.signup(
            username='******',
            email='*****@*****.**',
            password='******',
        )
        db.session.add(self.u)
        db.session.commit()

        self.rec = Recipe(name='Recipe')
        db.session.add(self.rec)
        db.session.commit()
Exemple #24
0
    def setUp(self):
        """Create test client, add sample data."""

        self.client = app.test_client()
        Recipe.query.delete()
        GroceryList.query.delete()
        User.query.delete()

        u = User.signup({
            'email': "*****@*****.**",
            'username': "******",
            'password': "******",
            'img_url': "www.test.com/test.jpg"
        })
        r = Recipe(title="test recipe", image="test image path")

        db.session.add_all([u, r])
        db.session.commit()
        g = GroceryList(user_id=u.id)
        db.session.add(g)
        db.session.commit()

        self.u = u
        self.u_id = u.id
        self.r = r
        self.r_id = r.id
        self.g = g
        self.g_id = g.id
        self.email = u.email
        self.username = u.username
        self.img_url = u.img_url
def addRecipe():
    if 'email' not in session:
        return redirect(url_for('login'))

    recForm = AddArticleForm()
    # Temporarily passing this message object in order to display an added message under the form.
    message = ""

    if request.method == 'POST':
        if not recForm.validate():
            return render_template('newrecipe.html',
                                   recForm=recForm,
                                   message=message)
        else:

            # The Recipe constructor adds each ingredient in this tuple as a child which handles the many-to-many relationship
            ingredients = recForm.recipeingredients.data
            newRec = Recipe(recForm.recipetitle.data, recForm.recipedesc.data,
                            ingredients, session['email'])

            # No Try/Catch here because the db is not configured to require unique titles
            db.session.add(newRec)
            db.session.commit()
            message = "Recipe added: " + newRec.recipetitle
            return redirect(url_for('index'))

    elif request.method == 'GET':
        return render_template('newrecipe.html',
                               recForm=recForm,
                               message=message)
Exemple #26
0
def save_recipe(username):
    """Save recipe to database"""
    if 'username' not in session:
        flash("Please login first", "danger")
        return redirect('/')

    recipe_data = request.get_json()['params']

    title = recipe_data['title']
    image = recipe_data['image']
    url = recipe_data['url']
    calories = recipe_data['calories']
    total_yield = recipe_data['yield']
    time = recipe_data['time']
    ingredients = recipe_data['ingredients']

    recipe = Recipe(title=title,
                    image=image,
                    url=url,
                    calories=calories,
                    total_yield=total_yield,
                    time=time,
                    ingredients=ingredients,
                    username=username)
    db.session.add(recipe)
    db.session.commit()

    return jsonify({'message': "Recipe saved!"})