예제 #1
0
def test_needed_ingredients_from_menu_are_accumulated():
    dish1 = Recipe(
        1, [Ingredient("x", Amount(1, U.r)),
            Ingredient("y", Amount(1, U.s))])
    dish2 = Recipe(
        1, [Ingredient("y", Amount(1, U.s)),
            Ingredient("z", Amount(1, U.t))])
    servings = [Serving(dish1, 2), Serving(dish2, 3)]
    ingredients = growser.needed_ingredients(servings)
    assert len(ingredients) == 3
    x, y, z = extract_amounts(ingredients, "xyz")
    assert x == Amount(2, U.r)
    assert y == Amount(5, U.s)
    assert z == Amount(3, U.t)
예제 #2
0
def fetch_recipe_and_ingredients(recipe_id):
    resp = dynamodb.query(
        TableName='recipes',
        KeyConditionExpression="PK = :pk AND SK BETWEEN :metadata AND :ingredients",
        ExpressionAttributeValues={
            ":pk": { "S": "RECIPE#{}".format(recipe_id) },
            ":metadata": { "S": "#METADATA#{}".format(recipe_id) },
            ":ingredients": { "S": "INGREDIENT$" },
        },
        ScanIndexForward=True
    )

    recipe = Recipe(resp['Items'][0])
    recipe.ingredients = [RecipeIngredientMapping(item) for item in resp['Items'][1:]]
    return recipe
예제 #3
0
def do_inserts():
    cat_arroces = Category(name="Arroces", description="Arrocitos")
    code = cat_arroces.put().urlsafe()
    cat_arroces.id = code
    cat_arroces.put()
    cat_pastas = Category(name="Pastas", description="Lorem ipsum")
    code = cat_pastas.put().urlsafe()
    cat_pastas.id = code
    cat_pastas.put()
    cat_sopas = Category(name="Sopas e cremas", description="Fresco, fresco")
    code = cat_sopas.put().urlsafe()
    cat_sopas.id = code
    cat_sopas.put()
    rec1 = Recipe(name="Arroz con chícharos",
                  category=cat_arroces,
                  servings=4,
                  ingredients=[Ingredient(name="Arroz", quantity="500gr"),
                               Ingredient(name="Chícharos", quantity="300gr")],
                  steps=["Cocemos o arroz", "Botámoslle os chícharos", "Servir en quente"])
    rec2 = Recipe(name="Macarróns con tomate",
                  category=cat_pastas,
                  servings=6,
                  ingredients=[Ingredient(name="Macarróns", quantity="600gr"),
                               Ingredient(name="Tomate frito", quantity="100gr")],
                  steps=["Cocemos os macarróns",
                         "Botámoslleo tomate frito",
                         "Servimos en quente"])
    rec3 = Recipe(name="Gazpacho andaluz",
                  category=cat_sopas,
                  servings=6,
                  ingredients=[Ingredient(name="Aceite de oliva", quantity="120cc"),
                               Ingredient(name="Auga", quantity="500cc"),
                               Ingredient(name="Dente de allo", quantity="2"),
                               Ingredient(name="Ovo duro", quantity="1"),
                               Ingredient(name="Miga de pan", quantity="100gr"),
                               Ingredient(name="Pepino", quantity="50gr"),
                               Ingredient(name="Pemento verdeo", quantity="50gr"),
                               Ingredient(name="Sal", quantity="1 pizca"),
                               Ingredient(name="Tomates naturais", quantity="1kg"),
                               Ingredient(name="Vinagre", quantity="60cc"),
                               Ingredient(name="Cebola picada", quantity="1/2")],
                  steps=[
                      "No bol da batidora ponse o aceite, a vinagre, a sal e ben cortados, os allos, o pepino e o pemento."
                      " Triturase todo ben e vaise metendo na batidora",
                      "Vaise incorporando o tomate, previamente escaldado e pelado, e siguese pasando pola batidora",
                      "Ponse o pan en remollo e escorese e engadeselle o anterior",
                      "Incorporase a auga para que non quede tan espeso e uns cubiños de xeo para que este mais grio",
                      "Servese en tazons e en diferentes pratos individuais. Disponse un pouco de pemento picado, a "
                      "cebola, o pepino, o tomate natural e o ovo duro, previamente cocido, e todo elo finalmente "
                      "picado para engadir se se desexa ao gazpacho"])
    rec1.put()
    rec2.put()
    rec3.put()
예제 #4
0
def find_recipes_by_base(base_spirit):
    resp = dynamodb.query(
        TableName='recipes',
        IndexName="BaseSpiritIndex",
        KeyConditionExpression="#base = :base",
        ExpressionAttributeNames={
            "#base": "base"
        },
        ExpressionAttributeValues={
            ":base": { "S": base_spirit },
        },
        ScanIndexForward=True
    )

    recipes = [Recipe(item) for item in resp['Items']]

    return recipes
예제 #5
0
    def search(chain):
        """
        Method that obtains all recipes that contain
        the string passed as parameter in the name attribute.
        @param chain: The search string.
        @return: List of recipes that match with the search string.
        """
        reload(sys)
        sys.setdefaultencoding("utf-8")

        def normalize(input_str):
            """
            Removes accents of a string.
            @param input_str: Original string.
            @return: Same string with all accents removed.
            """
            input_str = input_str.lower()
            nkfd_form = unicodedata.normalize('NFKD', unicode(input_str))
            return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])

        return [r for r in Recipe.query() if normalize(chain) in normalize(r.name)]
예제 #6
0
def get_all_recipes():
    """
    Fetch all recipes in the database
    :return: JSON data in the form of {"recipes":[<list of JSON objects representing the recipes and their ingredients>]}
    """
    recipes = Recipe().all()
    cursor = g.db.cursor()
    for recipe in recipes:
        id_val = recipe[Recipe.__keys__[0]]
        cursor.execute(
            "SELECT *\n"
            "FROM mongoose.food\n"
            "WHERE food_id IN (SELECT food_id\n"
            "                  FROM mongoose.ingredients\n"
            "                  WHERE recipe_id = %s)",
            (id_val,))
        ingredients = cursor.fetchall()
        recipe['ingredients'] = ingredients
    cursor.close()

    return jsonify({"recipes": recipes})
예제 #7
0
def get_recipe_by_name(rec_name):
    """
    Get all recipes that match a name
    :param rec_name: A string value with a recipe name
    :return: JSON data in the form of {"recipes":[<list of JSON objects representing the recipes and their ingredients>]}
    """
    recipes = Recipe().find_by_attribute("rec_name", rec_name, limit=-1)
    if not recipes:
        return jsonify(({"error": "No recipes with name \"{}\" found".format(rec_name)})), 404
    cursor = g.db.cursor()
    for recipe in recipes:
        id_val = recipe[Recipe.__keys__[0]]
        cursor.execute(
            "SELECT *\n"
            "FROM mongoose.food\n"
            "WHERE food_id IN (SELECT food_id\n"
            "                  FROM mongoose.ingredients\n"
            "                  WHERE recipe_id = %s)",
            (id_val,))
        ingredients = cursor.fetchall()
        recipe['ingredients'] = ingredients
    cursor.close()
    return jsonify({"recipes": recipes})
예제 #8
0
def get_recipe_by_id(rec_id):
    """
    Gets a single recipe by its id
    :param rec_id: The numeric id of the recipe to find
    :return: JSON object representing the recipe and its ingredient ids
    """
    recipe = Recipe().find_by_id(rec_id)
    if not recipe:
        return jsonify({"error": "No recipe with id {} found".format(rec_id)}), 404

    id_val = recipe[Recipe.__keys__[0]]
    cursor = g.db.cursor()
    cursor.execute(
        "SELECT *\n"
        "FROM mongoose.food\n"
        "WHERE food_id IN (SELECT food_id\n"
        "                  FROM mongoose.ingredients\n"
        "                  WHERE recipe_id = %s)",
        (id_val,))
    ingredients = cursor.fetchall()
    recipe['ingredients'] = ingredients
    cursor.close()
    return jsonify(recipe)
예제 #9
0
def recipe_update_create():
    """
    Take in a JSON object in the form of
    {
        "recipes":
        [
            {
                "rec_id": 1,
                "rec_name": "Chicken and Rice",
                "instructions": "Idk, ask mom",
                "category": <a string value of either entree, appetizer, or dessert>,
                "ingredients": [ <a list of ingredient ids>]
            }, ...
        ]
    }

    Where for each entry in "recipes" if there is a "rec_id" attribute,
    it is assumed that we are updating an existing recipe (because we wouldn't have the id otherwise),
    and the values given will update the record and its ingredients links in the database.

    Otherwise, if there is no "rec_id" for an object, the system will assume the values
    given are for a new record in the database and will create a new record.

    :return: A JSON object of {"recipes":[<list of recipes updated or created in the system>]}
    """
    if not request.json or len(request.json) == 0:
        return jsonify({"error": "No JSON supplied"}), 400
    id_column = Recipe.__keys__[0]
    ret_val = []
    rec = Recipe()
    j = request.json
    if not j.get('recipes', None):
        return jsonify({"error": "Invalid input schema"}), 400

    for recipe in j['recipes']:
        recipe_id = recipe.get(id_column, None)
        # Enforce enums
        if recipe.get("category", None) and recipe['category'] not in Recipe.__columns__['category']:
            return jsonify({
                "error": "Categories must be one of the following: {}".format(Recipe.__columns__['category'])}
            ), 400
        if recipe_id:
            rec.find_by_id(recipe_id)
            rec.update(**recipe)
            rec.flush()
        else:
            rec.create(**recipe)
        if recipe.get('ingredients', None):
            try:
                rec.ingredients = recipe['ingredients']
            except TypeError:
                return jsonify({
                    "error": "Ingredient entries must be a list of ids referencing food items in the database"
                }), 400
        ret_val.append(deepcopy(rec.data))
    return jsonify({"recipes": ret_val})
예제 #10
0
from functools import reduce
from operator import add

import pytest

from entities import Recipe, Ingredient, Amount, Serving, Unit, CompoundRecipe
import growser


class U:
    r = Unit("r")
    s = Unit("s")
    t = Unit("t")


recipe = Recipe(for_people=1, ingredients=[Ingredient("x", Amount(1, U.r))])
recipe2 = Recipe(for_people=1,
                 ingredients=[
                     Ingredient("x", Amount(1, U.r)),
                     Ingredient("y", Amount(2, U.s))
                 ])


def test_recipe_amount_for_more_people():
    scaled = growser.serve_for(2, recipe)
    assert scaled.ingredients[0].amount.number == 2


def extract_amounts(ingredient_list, ingredient_names):
    return map(
        lambda name: next(i for i in ingredient_list if i.name == name).amount,