Beispiel #1
0
    def test_recipe_as_selectable_from_yaml(self):
        """A recipe can be used as a selectable for a shelf
        created from yaml"""
        recipe = (Recipe(
            shelf=census_shelf,
            session=self.session).metrics("pop2000").dimensions("state"))

        yaml = """
        pop:
            kind: Metric
            field:
                value: pop2000
                aggregation: avg
        """

        recipe_shelf = Shelf.from_yaml(yaml, recipe)

        r = Recipe(shelf=recipe_shelf, session=self.session).metrics("pop")
        assert (r.to_sql() == """SELECT avg(anon_1.pop2000) AS pop
FROM
  (SELECT census.state AS state,
          sum(census.pop2000) AS pop2000
   FROM census
   GROUP BY state) AS anon_1""")
        assert r.dataset.tsv == """pop\r\n3147355.0\r\n"""
Beispiel #2
0
class BookTest(unittest.TestCase):
	mozzarella = Recipe('mozzarella_sticks', 3, 20, ['mozzarella', 'sticks'], "", "starter")
	nugget = Recipe('nugget', 4, 65, ['chicken', 'bread'], "", "starter")
	omelette = Recipe('omelette au fromage', 2, 10, ['eggs', 'cheese', 'pepper'], "", "lunch")
	fondant = Recipe('fondant', 4, 30, ['eggs', 'chocolate', 'butter'], "", "dessert")
	creation = datetime.datetime(2019, 4, 13, 00, 00, 00)
	last = datetime.datetime(2019, 5, 27, 00, 00, 00)
	recipe_list = {
		'starter': {
			mozzarella,
			nugget,
		},
		'lunch': {
			omelette,
		},
		'dessert': {
			fondant,
		}
	}
	test_book = Book("Text Book", last, creation, recipe_list)

	def test_get_recipe_by_type_method(self):
		gibberish_type = "blabla"
		integer_type = 123

		with self.assertRaises(SystemExit):
			self.test_book.get_recipes_by_type(gibberish_type)
			self.test_book.get_recipes_by_type(integer_type)

	def test_get_recipe_by_name_method(self):
		non_existing_name = "blabla"
		int_name = 123
		empty_name = ""

		with self.assertRaises(SystemExit):
			self.test_book.get_recipes_by_type(non_existing_name)
			self.test_book.get_recipes_by_type(int_name)
			self.test_book.get_recipes_by_type(empty_name)

	def test_add_recipe_method(self):
		non_recipe_object = "blabla"

		with self.assertRaises(SystemExit):
			self.test_book.add_recipe(non_recipe_object)

	def test_add_recipe_does_the_adding(self):
		recipe_to_add = Recipe('pasta', 1, 9, ['pasta', 'water'], "", 'lunch')
		self.test_book.add_recipe(recipe_to_add)
		type_of_added_recipe = recipe_to_add.recipe_type

		self.assertIn(recipe_to_add, self.test_book.recipes_list[type_of_added_recipe])

	def test_add_recipe_method_update_time(self):
		recipe_to_add = Recipe('cheesecake', 5, 45, ['cheese', 'cake'], "", 'dessert')
		last_update1 = self.test_book.last_update
		self.test_book.add_recipe(recipe_to_add)
		self.test_book.print_content_recipe_list()
		last_update2 = self.test_book.last_update

		self.assertNotEqual(last_update1, last_update2)
def test_possible_recipes(shopkeeper):
    assert shopkeeper.possible_recipes() \
           == {Recipe(quantity=1, name='Bandages',
                      ingredient1='Linen Cloth', ingredient2='Linen Cloth'),
               Recipe(quantity=1, name='Fire Rag',
                      ingredient1='Linen Cloth', ingredient2='Thick Oil'),
               Recipe(quantity=3, name='Bullet',
                      ingredient1='Iron Scrap', ingredient2='Thick Oil')}
Beispiel #4
0
	def test_recipe_cook_level(self):
		""" Testing if assigning wrong cook level to a recipe raises a system exit"""
		off_range = 6
		negative_range = -3

		with self.assertRaises(SystemExit):
			recette = Recipe(self.name, off_range, self.cook_time, self.ingredient, self.descr, self.rcp_type)
		with self.assertRaises(SystemExit):
			recette_2 = Recipe(self.name, negative_range, self.cook_time, self.ingredient, self.descr, self.rcp_type)
Beispiel #5
0
	def test_recipe_name(self):
		""" Testing if assigning an incorrect name to a recipe raises a system exit"""
		empty_name = ""
		integer_name = 123

		with self.assertRaises(SystemExit):
			recette = Recipe(empty_name, self.cook_level, self.cook_time, self.ingredient, self.descr, self.rcp_type)
		with self.assertRaises(SystemExit):
			recette_2 = Recipe(integer_name, self.cook_level, self.cook_time, self.ingredient, self.descr, self.rcp_type)
Beispiel #6
0
def recipe(recipe_name):
    if recipe_name == 'lager':
        lager = Recipe()
        lager.recipe_from_bxml('src/Recipe/xml/kalaslager.xml')
        return render_template('recipe.html', recipe=lager)

    if recipe_name == 'lipa':
        lipa = Recipe()
        lipa.recipe_from_bxml('src/Recipe/xml/lipa4_0.xml')
        return render_template('recipe.html', recipe=lipa)
Beispiel #7
0
def main():
    gateau = Recipe("Gateau", 2, 35, ['egg', 'foul'], 'dessert')
    tarte = Recipe("tarte", 2, 20, ['egg', 'lol'], 'dessert',
                   "C'est une tarte aux fraises")
    cookbook = Book('cookbook')
    cookbook.add_recipe(gateau)
    cookbook.add_recipe(tarte)
    cookbook.get_recipe_by_name('Gateau')
    recipes = cookbook.get_recipe_by_types('dessert')
    for recipe in recipes:
        print(recipe)
Beispiel #8
0
def add_cake():
    """ create and print a cake recipe, checks if it works with empty recipes """

    ingredients = ["chocolate", "flour", "sugar"]
    cake = Recipe("Cake", 2, 11, ingredients, "it's good", "dessert")
    new_dic = {
        "name": cake.name,
        "cooking_lvl": cake.cooking_lvl,
        "cooking_time": cake.cooking_time,
        "ingredients": cake.ingredients,
        "description": cake.description,
        "recipe_type": cake.recipe_type
    }

    ingredients = ["ice", "cream", "sugar"]
    icecream = Recipe("Ice-cream", 8, 11, ingredients, "it's good", "dessert")
    new_dic2 = {
        "name": icecream.name,
        "cooking_lvl": icecream.cooking_lvl,
        "cooking_time": icecream.cooking_time,
        "ingredients": icecream.ingredients,
        "description": icecream.description,
        "recipe_type": icecream.recipe_type
    }

    ingredients = ["vegetable", "cream"]
    soup = Recipe("Soup", 4, 15, ingredients, "it's good", "starter")
    new_dic3 = {
        "name": soup.name,
        "cooking_lvl": soup.cooking_lvl,
        "cooking_time": soup.cooking_time,
        "ingredients": soup.ingredients,
        "description": soup.description,
        "recipe_type": soup.recipe_type
    }

    ingredients = ["eggs", "salt"]
    omelet = Recipe("Omelet", 1, 5, ingredients, "it's good", "lunch")
    new_dic4 = {
        "name": omelet.name,
        "cooking_lvl": omelet.cooking_lvl,
        "cooking_time": omelet.cooking_time,
        "ingredients": omelet.ingredients,
        "description": omelet.description,
        "recipe_type": omelet.recipe_type
    }
    book = Book("Cookbook", datetime.datetime.today(),
                datetime.datetime.today())
    # [cake.name] name of new entry
    book.recipes_list[cake.recipe_type][cake.name] = new_dic
    book.recipes_list[icecream.recipe_type][icecream.name] = new_dic2
    book.recipes_list[soup.recipe_type][soup.name] = new_dic3
    book.recipes_list[omelet.recipe_type][omelet.name] = new_dic4
    return book
 def food_court(self):
     지원이 = Recipe('케이크')
     지원이.quantity = 1
     지원이.link = 'youtube.com'
     지원이.whatin = {'밀가루':'500', '계란':'100', '생크림':'200', '딸기':'300'}
     지원이.info = '맛있게 만드세요!'
     지원이.time = 60
     self.recipe_list.append(지원이)
     서연이 = Recipe('삼겹살김치볶음밥')
     서연이.quantity = 4
     서연이.link = ''
     서연이.whatin = {'삼겹살':'500', '김치':'100', '밥':'400'}
     self.recipe_list.append(서연이)
Beispiel #10
0
def main():
    cookbook = Book()
    print(cookbook.creation_date)
    print(cookbook.last_update)
    test = Recipe()
    cookbook.add_recipe(test)
    test = Recipe()
    cookbook.add_recipe(test)
    test = Recipe()
    cookbook.add_recipe(test)
    print(cookbook.get_recipe_by_type('lunch'))
    print(cookbook.creation_date)
    print(cookbook.last_update)
Beispiel #11
0
 def init_recipe(self):  #기존 음식
     떡볶이 = Recipe('떡볶이')
     떡볶이.people = 2
     떡볶이.video = 'youtube.com'
     떡볶이.ingredient = {'떡': '200', '고추장': '100', '물': '100', '어묵': '100'}
     self.recipe_list.append(떡볶이)  #객체 추가 (string x)
     카레 = Recipe('카레')
     카레.ingredient = {'카레가루': '50', '감자': '200', '당근': '100'}
     self.recipe_list.append(카레)
     파스타 = Recipe('파스타')
     파스타.contents = '맛있게 만드세요!'
     파스타.ingredient = {'면': '100', '토마토소스': '200'}
     self.recipe_list.append(파스타)
Beispiel #12
0
def main():
    tourte = Recipe('tourte', 5, 10, ['asd', 'egg'], 'Une tourte.', 'starter')
    tourte2 = Recipe('tourte', 5, 10, ['asd', 'egg'], 'Une tourte.', 'dessert')
    tourte3 = Recipe('test3', 5, 10, ['asd', 'egg'], 'Une tourte.', 'dessert')
    # print(tourte)

    book = Book('Livre')
    book.add_recipe(tourte)
    book.add_recipe(tourte2)
    book.add_recipe(tourte3)
    print(book.get_recipe_by_name('tourte'))
    print(book.get_recipe_by_name('tourte'))
    print(book.get_recipe_by_name('test3'))
def test_book():
    # New book
    grand_ma = Book("Grandma recipe collection")
    print(grand_ma.__dict__, end="\n\n")

    # Adding recipes
    time.sleep(.5)
    grand_ma.add_recipe(Recipe("Chocolate cake", 2, 45, ["chocolate",
                               "flavour"], "dessert"))
    grand_ma.add_recipe(Recipe("Apple pie", 3, 30, ["apple", "flavour"],
                               "dessert"))

    # Checking create and update time
    print("grand_ma.creation_date:", grand_ma.creation_date)
    print("grand_ma.last_update:", grand_ma.last_update, end="\n\n")

    # Recipe by type
    for rec in grand_ma.get_recipes_by_types("dessert").values():
        print(rec, end="\n\n")

    # Empty type
    print(grand_ma.get_recipes_by_types("lunch"), end="\n\n")

    # Recipe by name
    print(grand_ma.get_recipe_by_name("Apple pie").__dict__, end="\n\n")

    # ~~~~~~~~~~~~
    # Errors
    # ~~~~~~~~~~~~

    # Wrong recipe type
    try:
        grand_ma.get_recipes_by_types("panda")
        print("~~~ ERROR ~~~")
    except BookException as e:
        print(e)

    # Name doesn't exist
    try:
        grand_ma.get_recipe_by_name("Foie gras poilé")
        print("~~~ ERROR ~~~")
    except BookException as e:
        print(e)

    # Adding random things
    try:
        grand_ma.add_recipe("Fais les backs")
        print("~~~ ERROR ~~~")
    except BookException as e:
        print(e)
Beispiel #14
0
def main():
    tourte = Recipe("Lasana", 2, 20, ["leche", "huevos", "jamon"],
                    "MEjor receta", 'dessert')
    tourte2 = Recipe("Pizza", 2, 20, ["leche", "huevos", "jamon"],
                     "MEjor receta", 'lunch')
    to_print = str(tourte)
    #print(to_print)

    libro = Book("Librito")
    libro.add_recipe(tourte)
    libro.add_recipe(tourte2)
    recipe = libro.get_recipes_by_types("lunch")
    receta = libro.get_recipe_by_name("Pizzza")
    print(recipe)
Beispiel #15
0
	def test_recipe_ingredients(self):
		""" Testing if assigning wrong ingredients to a recipe raises a system exit"""
		empty_ingredients = []
		many_empty_ingredients = ['', '', '']
		different_type_ingredients = ['eggs', 'fromage', 12345]
		non_list_ingredients = "ingredients"

		with self.assertRaises(SystemExit):
			recette = Recipe(self.name, self.cook_level, self.cook_time, empty_ingredients, self.descr, self.rcp_type)
		with self.assertRaises(SystemExit):
			recette_2 = Recipe(self.name, self.cook_level, self.cook_time, many_empty_ingredients, self.descr, self.rcp_type)
		with self.assertRaises(SystemExit):
			recette_3 = Recipe(self.name, self.cook_level, self.cook_time, different_type_ingredients, self.descr, self.rcp_type)
		with self.assertRaises(SystemExit):
			recette_4 = Recipe(self.name, self.cook_level, self.cook_time, non_list_ingredients, self.descr, self.rcp_type)
Beispiel #16
0
def book_test():
    book = Book("cookbook")
    print("Cookbook creation date: " + book.creation_date.strftime("%d/%m/%y"))
    rec = Recipe("Sandwich", 1, 10, ["Ham", "Bread"], "Meal", "lunch")
    book.add_recipe(rec)
    rec = Recipe("Cereals", 1, 2, ["Cereals", "Milk"],
                 "To be eaten in the morning", "starter")
    book.add_recipe(rec)
    rec = Recipe("Cake", 3, 20, ["Flour", "Butter", "Eggs"], "After meal",
                 "dessert")
    book.add_recipe(rec)
    # book.print_all()
    book.get_recipes_by_type("lunch")
    rec = book.get_recipe_by_name("Cereals")
    print(rec)
Beispiel #17
0
 def food_court(self):
     해인이 = Recipe('케이크')
     해인이.quantity = 1
     해인이.link = 'youtube.com'
     해인이.whatin = {'밀가루': '500', '계란': '100', '생크림': '200', '딸기': 300}
     해인이.info = "맛있게 드세용"
     해인이.time = 60
     self.recipe_list.append(해인이)
     서연이 = Recipe('삼겹살 볶음밥')
     서연이.quantity = 1
     서연이.whatin = {'삼겹살': '100', '김치': '100', '밥': '100'}
     서연이.link = 'youtube.com'
     서연이.info = "맛있게 드세용"
     서연이.time = 60
     self.recipe_list.append(서연이)
    def generate(self):
        """ Generates a List of recipes From the XML"""

        recipes = []

        for child in self.root.findall('recipe'):
            name = child.find('ti').text
            process = child.find('pr').text

            ingredients = []
            for i in child.findall('in'):
                description = i.text.lower()

                if " or " in description:  # We have different options in one
                    options = self._separate(description)

                    for option in options:
                        ingredient = self._parse_ingredient(option)
                        ingredients.append(ingredient)

                else:
                    ingredient = self._parse_ingredient(description)
                    ingredients.append(ingredient)

            recipe = Recipe(name.lower(), ingredients, process.lower())
            recipes.append(recipe)

        return recipes
def get_recipe(recipe_url):
    #Variabales
    name = ""
    ingredients = []
    cooking_method = []

    #Open URL using urllib
    url = "https://www.bbc.co.uk" + recipe_url
    print url

    recipe_page = urllib.urlopen(url)

    #Use BeautifulSoup to get html text
    soup = BeautifulSoup(recipe_page, 'lxml')

    #Retrieve recipe name
    name = soup.find("h1", {
        'class': 'content-title__text'
    }).text.encode('utf-8')
    print name
    #Retrieve each list of recipe ingredients
    for ingredient in soup.find_all('ul',
                                    {'class': 'recipe-ingredients__list'}):
        #Convert text from unicode to python str
        ingredients.append(ingredient.text.encode('utf-8'))

    #Retrieve method for cooking the dish
    for method in soup.find_all('p',
                                {'class': 'recipe-method__list-item-text'}):
        #Convert text from unicode to python str
        cooking_method.append(method.text.encode('utf-8'))

    recipe_item = Recipe(name, ingredients, url)
    return recipe_item
Beispiel #20
0
 def get_recipes_for_user(self, userid):
     result = self.get_recommendations(userid, 10)
     if not result:
         return []
     print result
     recipes = [res.recipe_id for res in result]
     return Recipe().list_from_ids(recipes)
Beispiel #21
0
def choose(book, str):
    if str == "1":
        name = input("Name: ")
        lvl = input("Level: ")
        time = input("Time to make: ")
        ingredient = input("Ingredients: ")
        description = input("Description: ")
        type = input("Type (starter, lunch, dessert): ")
        if not type == "starter" and not type == "lunch" and not type == "dessert":
            print("The recipe type must be starter, lunch, or dessert.")
            exit()
        new = Recipe(name, lvl, time, ingredient, description, type)
        book.add_recipe(new)
        choose(
            book,
            input(
                "Hi ! What do you want to do?\n1/ Add a recipe\n2/ Get recipes by names\n3/ Get recipes by types\n4/ Exit\n"
            ))
    elif str == "2":
        name = input("Name of the recipe you are looking for: ")
        book.get_recipes_by_name(name)
    elif str == "3":
        type = input("Type (starter, lunch, dessert): ")
        if not type == "starter" and not type == "lunch" and not type == "dessert":
            print("The recipe type must be starter, lunch, or dessert.")
            exit()
        book.get_recipes_by_types(type)
    elif str == "4":
        exit()
    else:
        choose(
            book,
            input(
                "You failed...\n1/ Add a recipe\n2/ Get recipes by names\n3/ Get recipes by types\n4/ Exit\n"
            ))
Beispiel #22
0
    def test_recipe_with_select_from(self):
        from recipe import Dimension, Metric

        shelf = Shelf(
            {
                "region": Dimension(StateFact.census_region_name),
                "pop": Metric(func.sum(Census.pop2000)),
            },
            select_from=join(Census, StateFact,
                             Census.state == StateFact.name),
        )

        assert shelf.Meta.select_from is not None

        r = (Recipe(shelf=shelf,
                    session=self.session).dimensions("region").metrics("pop"))

        assert r._select_from is not None

        assert (
            r.to_sql() == """SELECT state_fact.census_region_name AS region,
       sum(census.pop2000) AS pop
FROM census
JOIN state_fact ON census.state = state_fact.name
GROUP BY region""")
        assert (r.dataset.tsv == """region\tpop\tregion_id\r
Northeast\t609480\tNortheast\r
South\t5685230\tSouth\r
""")
        assert len(r.all()) == 2
Beispiel #23
0
def make_request(params):
    '''Make a request to the Web API using the baseurl and params

    Parameters
    ----------
    params: dict
        A dictionary of param:value pairs

    Returns
    -------
    list
        the data returned from making the request in the form of
        a list
    '''

    search_url = BASE_URL + "?q=" + params["q"] +\
            "&app_id=" + API_ID + "&app_key=" + API_KEY +\
                f"&cuisineType={params['cuisineType']}"
    response = requests.get(search_url).json()
    cache_list = []
    for recipe_json in response['hits']:
        recipe = Recipe(recipe_json)
        cache_list.append(recipe.to_json())

    return cache_list
Beispiel #24
0
	def parseContent(self, content, link):
	
		# Get the content of the current page
		currentPageInfo = BeautifulSoup(content, "html.parser")
		print("Parsing: ", link)
		new_recipe = Recipe()
		new_recipe.setURL(link)
		
		# Find the ingredients of the recipe
		for span in currentPageInfo.find_all('span',itemprop="ingredients"):
		
			if(span.string not in self.ingredients):
				self.ingredients.append(span.string)
			
				
		description = currentPageInfo.find("meta",  property="og:description")
		
		new_recipe.setDescription(description["content"])
				
		new_recipe.setIngredients(self.ingredients)
		
		for time in currentPageInfo.find_all('span', {'class' : 'prepTime__item--time'}):
			new_recipe.setPrep(time.string)
			
		for calories in currentPageInfo.find_all('span', itemprop="calories"):
			new_recipe.setCalories(calories.string.strip(";"))
			
		new_recipe.setImage(currentPageInfo.find_all("meta", property="og:image")[0]["content"])
			
		self.recipes.append(new_recipe)
		
		self.ingredients = []
Beispiel #25
0
def main():
    recipes = []

    # read the text recipes into a list of Recipe objects
    for filename in glob.glob("resources/input/*.txt"):
        recipes.append(Recipe(ingredients_from_file(filename)))

    # get number of generations from command line; default to 10
    if len(sys.argv) > 1:
        num_generations = int(sys.argv[1])
    else:
        num_generations = 10

    # evolve our recipes
    for i in range(num_generations):
        new_recipes = fill_generation(recipes)
        new_population = select_new_generation(recipes, new_recipes)
        recipes = new_recipes

    # create our output file
    os.makedirs("output", exist_ok=True)

    # output the generated recipes to text files
    for i in range(len(recipes)):
        with open("output/new_recipe_" + str(i) + ".txt", "w") as file:
            file.write(str(new_population[i]))
def main():
    parser = argparse.ArgumentParser(
        prog='plexlibrary',
        description=("This utility creates or maintains a Plex library "
                     "based on a configuration recipe."),
        usage='%(prog)s [options] [<recipe>]',
    )
    parser.add_argument('recipe', nargs='?',
                        help='Create a library using this recipe')
    parser.add_argument(
        '-l', '--list-recipes', action='store_true',
        help='list available recipes')
    parser.add_argument(
        '-s', '--sort-only', action='store_true', help='only sort the library')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args()
    if args.list_recipes:
        list_recipes()
        sys.exit(0)

    if args.recipe not in recipes.get_recipes():
        print("Error: No such recipe")
        list_recipes()
        sys.exit(1)

    r = Recipe(args.recipe)
    r.run(args.sort_only)

    print("Done!")
Beispiel #27
0
    def get(self):
        recname = "Fried Chicken"
        rec = Recipe(id=recname,
                     name=recname,
                     totalprice=8.50,
                     totaltime=0.5,
                     healthrating=2,
                     notes="Don't cook on high heat!")
        rec_key = rec.put()

        ingred = Ingredient(parent=rec.key,
                            id="Chicken",
                            name="Chicken",
                            price=2.50)
        ingred.put()

        ingred1 = Ingredient(parent=rec.key,
                             id="Flour",
                             name="Flour",
                             price=0.10)
        ingred1.put()

        ##key = ndb.Key("Recipe", "Fried Chicken")
        ##key.delete()

        self.response.write("Data filled!")
Beispiel #28
0
def main():
    ingredients = ['flour', 'eggs', 'milk']
    test_recipe('cake', 1, 10, ingredients, 'A delicious dessert',
                Recipe.RECIPE_TYPES[2])
    test_recipe('cake', 1, 10, ingredients, None, Recipe.RECIPE_TYPES[2])
    test_recipe('', 1, 10, ingredients, 'A delicious dessert',
                Recipe.RECIPE_TYPES[2])
    test_recipe(None, 1, 10, ingredients, 'A delicious dessert',
                Recipe.RECIPE_TYPES[2])
    test_recipe('cake', None, 10, ingredients, 'A delicious dessert',
                Recipe.RECIPE_TYPES[2])
    test_recipe('cake', '2', 10, ingredients, 'A delicious dessert',
                Recipe.RECIPE_TYPES[2])
    test_recipe('cake', 6, 10, ingredients, 'A delicious dessert',
                Recipe.RECIPE_TYPES[2])
    test_recipe('cake', 1, -4, ingredients, 'A delicious dessert',
                Recipe.RECIPE_TYPES[2])
    test_recipe('cake', 1, 10, [1, 3, 'Hola'], 'A delicious dessert',
                Recipe.RECIPE_TYPES[2])
    test_recipe('cake', 1, 10, ingredients, 300, Recipe.RECIPE_TYPES[2])
    test_recipe('cake', 1, 10, ingredients, 'A delicious dessert', 'Dinner')

    cake = Recipe('cake', 1, 10, ingredients, 'A delicious dessert',
                  Recipe.RECIPE_TYPES[2])
    book = Book("Libro")
    print(book)
    book.add_recipe(cake)
    print(book)
    print(book.get_recipe_by_name(cake.name))
    print(book.get_recipes_by_types(cake.recipe_type))
    print(book.get_recipes_by_types(Recipe.RECIPE_TYPES[0]))
Beispiel #29
0
def parse_recipe(page):
	recipe_ingredients = getIngredients(page)

	regex = re.compile("<h1 id=\"itemTitle\" class=\"plaincharacterwrap fn\" itemprop=\"name\">(.*?)</h1>")
	recipe_title = re.findall(regex, page)[0]

	tool_list = hc_make_tool_list()
	method_list = hc_make_method_list()

	directions = getDirections(page)
	recipe_tools = select_tools(directions, tool_list)

	methods = select_methods(directions, method_list)

	if len(methods) > 1:
		other_methods = methods[1:]
	else:
		other_methods = []

	if len(methods) > 0:
		main_method = methods[0]
	else:
		main_method = "none found"

	res = Recipe(recipe_title, recipe_ingredients, recipe_tools, main_method, other_methods, directions)
	return res
Beispiel #30
0
def load():
    try:
        query = request.args["query"]
        logging.info("Requesting from MealDB with query {}".format(query))
        res = requests.get(query)
        meals = res.json().get("meals", [])
        loaded_recipes = []
        if res.status_code == 200:
            for each_meal in meals:
                recipe = Recipe()
                recipe.load_from_json(**each_meal)
                recipe.save()
                loaded_recipes.append(recipe)
            return render_template("home.html",
                                   loaded_recipes=loaded_recipes,
                                   query=query)
        else:
            return "<h4>MealDB query returned with response code {}, with message </h4>{}".format(
                res.status_code, res.text)
    except requests.exceptions.ConnectionError:
        logging.error("connection error")
        return "Could not make contact with MealDB server"
    except requests.exceptions.Timeout:
        logging.error("timed out")
        return "Request to MealDB timed out"
    except requests.exceptions.RequestException as e:
        logging.error("Error: {}".format(e))
        return "Something happened check logs"