Пример #1
0
def createIngredient():
    ingredients = Ingredients()
    params = {}
    if request:
        params["dish_id"] = request.args.get('dish_id', '')
        params["name"] = request.args.get('name', '')
        params["amount"] = request.args.get('amount', '')
        params["unit"] = request.args.get('unit', '')
        dish_id = ingredients.create(params)
        return redirect(url_for('formEditDish', dish_id=params["dish_id"]))
    else:
        return "Fehler"
Пример #2
0
def deleteIngredient():
    ingredients = Ingredients()
    params = {}
    if request:
        dish_id = request.args.get('dish_id', '')
        name = request.args.get('name', '')
        ingredients.delete(dish_id, name)
        ingredients.__del__
        del (ingredients)
        # return redirect(url_for('getTags'), msg='Tag created')
        return redirect(url_for('formEditDish', dish_id=dish_id))
        # return "{0}".format(params)
    else:
        return "Fehler"
Пример #3
0
def formEditDish():
    """ Zeigt ein Formular zur bearbeitung eines Gerichts an. Parameter: dish_id """

    # Abfragen, ob Daten übergeben wurden
    if request:
        dish_id = request.args.get('dish_id', '')
    else:
        return "Error"

    # Falls dish_id als String übergeben wurde -> in Integer umwandeln

    if type(dish_id) == str:
        dish_id = int(dish_id)

    # Gericht & Tags mit Namen laden
    dishes = Dishes()
    dish = dishes.getDish(dish_id)[0]
    taggedDishes = TaggedDishes()
    tag_for_dish = taggedDishes.list_with_names(dish['dish_id'])
    dish['tags'] = tag_for_dish

    # Allgemeine Tags laden
    tags = Tags()
    allTags = tags.list_tags()
    countTags = len(allTags)

    # Zutaten für das Gericht laden
    ingredientsAll = Ingredients()
    ingredients = ingredientsAll.list(dish_id)

    # Alle Namen und Einheiten der Zutaten laden
    suggestions = ingredientsAll.get_suggestions()
    # print(suggestions)

    # Tags selektieren
    for index in range(len(allTags)):
        for tag2 in tag_for_dish:
            if allTags[index]['tag_id'] == tag2['tag_id']:
                allTags[index]['selected'] = " selected"

    # Template füllen und zurückgeben
    return render_template('formEditDish.html',
                           allTags=allTags,
                           countTags=countTags,
                           dish=dish,
                           ingredients=ingredients,
                           ingredientsCount=len(ingredients),
                           suggestions=suggestions)
Пример #4
0
def updateIngredients(recipe_id):

    content = request.get_json()

    try:
        Ingredients.query.filter_by(recipe_id=recipe_id).delete()
        db.session.commit()
    except Exception as e:
        return str(e)

    print(content)
    for i in range(0, len(content), 1):
        quantity = content[i].get('quantity')
        name = content[i].get('name')
        notes = content[i].get('info')
        try:
            ingredients = Ingredients(
                recipe_id=recipe_id,
                ingredient_id=i+1,
                name=name,
                quantity=quantity,
                notes=notes
            )
            db.session.add(ingredients)
            db.session.commit()
        except Exception as e:
            return str(e)
    return "ingredients added"
Пример #5
0
def getIngredients(data, recipeId):
    ingredients = []
    for i in range(1, 20, 1):
        try:
            name = data[INGREDIENT_NAME_ID + str(i)]
            unit = data[INGREDIENT_UNIT_ID + str(i)]
            amount = data[INGREDIENT_AMOUNT_ID + str(i)]
            ingredients.append(Ingredients(recipeId, name, unit, amount))
        except:
            break
    return ingredients
Пример #6
0
def showDish(dish_id):
    if type(dish_id) is int:
        dishes = Dishes()
        dish = dishes.getDish(dish_id)[0]
        taggedDishes = TaggedDishes()
        tag_for_dish = taggedDishes.list_with_names(dish['dish_id'])
        dish['tags'] = tag_for_dish
        if dish['note']:
            dish['note'] = dish['note'].replace('\n', '<br>')
        else:
            dish['note'] = ''
        for tag in dish['tags']:
            print(tag)
        ingredientsAll = Ingredients()
        ingredients = ingredientsAll.list(dish_id)
        return render_template('dish.html',
                               dish=dish,
                               ingredients=ingredients,
                               ingredientsCount=len(ingredients))
    else:
        returnText = "Detailansicht eines Gerichts: Fehler"
Пример #7
0
    def test_add_remove_change_ingred(self):

        new_ingredient = Ingredients(name='Test Ingred')
        new_ingredient.id = 10000

        db.session.add(new_ingredient)

        ingred = Ingredients.query.get(10000)

        self.assertEqual(ingred.id, 10000)
        self.assertEqual(ingred.name, 'Test Ingred')

        ingred.name = 'Change Ingred'
        db.session.commit()

        self.assertEqual(ingred.name, 'Change Ingred')

        db.session.delete(ingred)
        db.session.commit()
        delete_ingred = Ingredients.query.filter(
            Ingredients.name == 'Test2 Ingred').first()

        self.assertEqual(delete_ingred, None)
Пример #8
0
    def add_ingredient():
        res = request.get_json()
        print(res)

        try:
            ingredient = Ingredients()

            if 'name' in res:
                ingredient.name = res['name']
            else:
                raise Exception("it's missing the ingredient name key:value")

            if 'quantity' in res:
                ingredient.quantity = res['quantity']
            else:
                raise Exception(
                    "it's missing the ingredient quantity key:value")

            if 'meal_id' in res:
                ingredient.meal_id = 1
            else:
                ingredient.meal_id = 1

            ingredient.insert()

        except Exception as e:
            print(e)
            return jsonify({
                'status': False,
                'ingredient': 'there was a problem with the request'
            })

        new_ingredient = Ingredients.query.filter(
            Ingredients.name == res['name'],
            Ingredients.meal_id == 1).one_or_none()
        print('-----------------', new_ingredient)

        return jsonify({'status': True, 'ingredient': ingredient.format()})
Пример #9
0
def addIngredients():

    content = request.get_json()
    recipe_id = content.pop(len(content) - 1)

    print(content)
    for i in range(0, len(content), 1):
        quantity = content[i].get('quantity')
        name = content[i].get('name')
        notes = content[i].get('info')
        try:
            ingredients = Ingredients(
                recipe_id=recipe_id,
                ingredient_id=i+1,
                name=name,
                quantity=quantity,
                notes=notes
            )
            db.session.add(ingredients)
            db.session.commit()
        except Exception as e:
            return str(e)
    return "ingredients added"
Пример #10
0
def volumes(week):
    SQL_quer_numb = 'SELECT number from FORECAST WHERE week==' + str(
        '\''
    ) + week + str(
        '\''
    )  #at first I write sql queries on the forecast database to get the number and the slot of the mealkits for the given week
    SQL_quer_slot = 'SELECT slot from FORECAST WHERE week==' + str(
        '\''
    ) + week + str(
        '\''
    )  #the str('\'') was the only way i found to put '' in a string, without messing everything up
    slots = []
    volume = []
    SlotVol = []
    Menu_id_amount = []  #=data21
    Ingredient_amount = []
    response = []
    slots_dat = forecast_db.execute_sql(SQL_quer_slot)
    numbers_dat = forecast_db.execute_sql(SQL_quer_numb)
    for value, in slots_dat:
        slots += [value]
    for value, in numbers_dat:
        volume += [value]
    for i in range(len(volume)):
        SlotVol += [
            (slots[i], volume[i])
        ]  #this list is composed of tuples of the slot of the menu, and the amount of it that is forecasted
    SlotVol = SlotVol + SlotVol  #there are 20 slots for every week, but there are two versions of every mealkit (I'm not sure I understood that part though), so I had to append this list with itself
    query_idMenu = Menu.select(Menu.id).where(
        Menu.week == week
    )  #this query returns the menus of the boxes that are planned to be prepared the week of the query
    query_recipies = Mealkit.select(Mealkit.recipe).where(
        (Mealkit.menu << query_idMenu) & (Mealkit.slot << slots)
    )  #this query gets the recipes' id of the selected menus, given the corresponding slots
    recipes_id = [
        i for i, in query_recipies.tuples()
    ]  #this line simply gets the data of the query_recipes in a variable
    for i in range(
            len(recipes_id)
    ):  #the idea of the next two lines is to create a list of tuples, in order to multiply the final number of each ingredient by the number of times this recipe needs to be made
        Menu_id_amount += [
            (recipes_id[i], SlotVol[i][1])
        ]  #the id of the recipes, and the number of menus at this id (0 : recipes id, 1 : number of recipes that needs to be made)
    for i in range(
            len(recipes_id)
    ):  #the next step is to get the sku and the quantity needed from the Mealkitingredient table, given the id of the recipe
        qur_sku = MealkitIngredient.select(MealkitIngredient.sku).where(
            MealkitIngredient.mealkit == recipes_id[i]
        )  #the first request queries the sku of the ingredients needed, given that the mealkit id corresponds
        qur_quant = MealkitIngredient.select(
            MealkitIngredient.qty_needed
        ).where(
            MealkitIngredient.mealkit == recipes_id[i]
        )  #the second request queries the quantity of ingredient need for one recipe
        data_sku = [i for i, in qur_sku.tuples()
                    ]  #here I just convert the query into data
        data_quant = [i for i, in qur_quant.tuples()]  #same thing here
        for j in range(
                len(data_sku)
        ):  #since recipes can use different ingredients, I need to do a loop for each recipe, in order to get the number of ingredients needed
            Ingredient_amount += [
                (data_sku[j], data_quant[j] * Menu_id_amount[i][1])
            ]  #0 : id ingredient, 1 : number needed
    for i in range(
            len(Ingredient_amount)
    ):  #now the final part : i just need to get the name of each ingredient
        qur_name = Ingredients.select(Ingredients.name).where(
            Ingredients.id == Ingredient_amount[i][0])  #query to get the name
        data_name = [i for i, in qur_name.tuples()]  #data conversion
        name = {
            'name': data_name[0]
        }  #I then create dictionnary for each key, I'm not sure if it was necessary but it worked
        sku = {'sku': Ingredient_amount[i][0]}
        quantity = {'quantity': Ingredient_amount[i][1]}
        name.update(quantity)  #here I concatenate the tables
        name.update(sku)
        response += [
            name
        ]  #here i simply put the dictionnary in the table, once again, not sure if that was necessary but it worked
    return json.dumps(response)
Пример #11
0
from main import app
from models import db, Ingredients
import csv

db.create_all(app=app)

with open('ingrediants.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=',')

    for row in reader:
        if row['item'] == '':
            row['item'] = None
        if row['price'] == '':
            row['price'] = None

            ingrediants = Ingredients(item=row['item'], price=row['price'])
            db.session.add(item)
            db.session.commit()
print('database initialized!')
Пример #12
0
    def post_meal():
        res = request.get_json()
        print(res)

        try:
            if 'ingredients' in res:
                for ing in res['ingredients']:
                    ingredient = Ingredients()
                    if 'name' in ing:
                        ingredient.name = ing['name']
                    else:
                        raise Exception(
                            "it's missing the ingredient name key:value")
                    if 'quantity' in ing:
                        ingredient.quantity = ing['quantity']
                    else:
                        raise Exception(
                            "it's missing the ingredient quantity key:value")
                    if 'meal_id' in ing:
                        ingredient.meal_id = ing['meal_id']
                    else:
                        raise Exception(
                            "it's missing the ingredient meal_id key:value")

                ingredient.insert()

            meal = Meals()
            if 'category' in res:
                meal.category = res['category']
            else:
                raise Exception("it's missing the meal category key:value")
            if 'title' in res:
                meal.title = res['title']
            else:
                raise Exception("it's missing the meal title key:value")
            if 'affordability' in res:
                meal.affordability = res['affordability']
            else:
                raise Exception(
                    "it's missing the meal affordability key:value")
            if 'complexity' in res:
                meal.complexity = res['complexity']
            else:
                raise Exception("it's missing the meal complexity key:value")
            if 'imageUrl' in res:
                meal.imageUrl = res['imageUrl'],
            else:
                raise Exception("it's missing the meal imageUrl key:value")
            if 'duration' in res:
                meal.duration = res['duration']
            else:
                raise Exception("it's missing the meal duration key:value")
            if 'steps' in res:
                meal.steps = res['steps']
            else:
                raise Exception("it's missing the meal steps key:value")
            if 'glutenfree' in res:
                meal.glutenfree = res['glutenfree']
            else:
                raise Exception("it's missing the meal glutenfree key:value")
            if 'vegan' in res:
                meal.vegan = res['vegan']
            else:
                raise Exception("it's missing the meal vegan key:value")
            if 'vegetarian' in res:
                meal.vegetarian = res['vegetarian']
            else:
                raise Exception("it's missing the meal vegetarian key:value")
            if 'lactosefree' in res:
                meal.lactosefree = res['lactosefree']
            else:
                raise Exception("it's missing the meal lactosefree key:value")

            meal.insert()

        except Exception as e:
            print('--------------', e)
            return jsonify({
                'status': False,
                'meals': 'there was a problem with the request'
            })

        return jsonify({'status': True, 'meals': meal.format()})
Пример #13
0
def addToWunderlist():
    # Alle Zutaten der Gerichte der angezeigten Woche zu Wunderlist hinzufügen
    #
    # input: Angezeigte Woche
    #
    # -> Alle Gerichte der Woche holen
    #
    # -> Alle Zutaten der Gerichte sammeln und gleiche Zutaten kombinieren
    #
    # -> Zutaten per API zu Wunderlist hinzufügen
    try:
        choosenDate = datetime.strptime(request.args.get('date', ''),
                                        "%Y-%m-%d").date()
    except:
        choosenDate = date.today()
    monday = getMonday(choosenDate)
    day = monday.day
    year = monday.strftime("%Y")
    # week = [(monday+timedelta(days=0)).day, (monday+timedelta(days=1)).day, (monday+timedelta(days=2)).day, (monday+timedelta(days=3)).day, (monday+timedelta(days=4)).day, (monday+timedelta(days=5)).day, (monday+timedelta(days=6)).day]
    # weekdays = {(monday+timedelta(days=0)).day:'Montag', (monday+timedelta(days=1)).day:'Dienstag', (monday+timedelta(days=2)).day:'Mittwoch', (monday+timedelta(days=3)).day:'Donnerstag', (monday+timedelta(days=4)).day:'Freitag', (monday+timedelta(days=5)).day:'Samstag', (monday+timedelta(days=6)).day:'Sonntag'}
    dishes = Dishes()
    dishes_for_wunderlist = {}
    daysObject = Days()
    ingredientsObject = Ingredients()
    html = "bla"
    ingredients_for_wunderlist = []
    ingredients = {}
    ingredients_obj = []
    for day in range(0, 7):
        actualDay = monday + timedelta(days=day)
        dishesperDay = daysObject.list(actualDay)
        for dish in dishesperDay:
            # print(dish)
            dish_ingredients = ingredientsObject.list(dish['dish_id'])
            for ing in dish_ingredients:
                if not ing["amount"]:
                    continue
                amount = ing['amount']
                if amount % 1 == 0:
                    amount = int(amount)
                ing['amount'] = amount
                element_index = next(
                    (index for (index, d) in enumerate(ingredients_obj)
                     if d["name"] == ing['name']), None)
                if element_index:
                    print("Gefunden" + ing['name'])
                    ingredients_obj[element_index]['amount'] += amount
                else:
                    ingredients_obj.append(ing)

    # Zutaten sortieren
    ingredients_obj.sort(key=operator.itemgetter('name'))

    for ing in ingredients_obj:
        if ing['unit'] + " " + ing['name'] in ingredients:
            ingredients[ing['unit'] + " " + ing['name']] += amount
        else:
            ingredients[ing['unit'] + " " + ing['name']] = amount
    for key, value in ingredients.items():
        if not addTodoListToWunderlist("{0} {1}".format(value, key)) == 201:
            return "Error!"

    # Test, der eine einzelne Todo erstellt
    # if not addTodoListToWunderlist("2.0 Stück Chilischote") == 201:
    #          return "Error!"
    return redirect(
        url_for('displayWeek',
                message='Zutaten wurden zur Wunderlist hinzugefügt'))