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()
def load_pickled_data(): with open('cocktails.pkl', 'rb') as f: pickled_cocktails = pickle.load(f) for c in pickled_cocktails: # instantiate and add cocktail cocktail = Cocktail(name=c.name, glass=c.glass, recipe=c.recipe, image=c.image) db_session.add(cocktail) # add each ingredient that is not already in db for i in c.ingredients: ingredient = Ingredient.query.filter(Ingredient.name==i[0]).one_or_none() if ingredient is None: image_name = i[0].replace(' ', '+').replace('/', '\\') image_path = '{0}/{1}'.format('ingredients', image_name) ingredient = Ingredient(i[0], image_path) db_session.add(ingredient) # add the amount for each ingredient amount = Amount(cocktail, ingredient, i[1]) db_session.add(amount) # commit unpickled cocktail goodness db_session.commit()
def backend(): if request.method == "POST": search_name = request.form["ingredient"] es = init_search() result = ingredient_search(search_name, es) if result: name = result[0] about = result[1] safety = result[2] function = result[3] else: name = about = safety = function = None print(name) print("foo0 " + about) new_ingredient = Ingredient(name, about, safety, function) print("foo1 " + about) db_session.add(new_ingredient) print("foo2 " + about) db_session.commit() data = { "name": new_ingredient.name, "about": new_ingredient.about, "safety": new_ingredient.safety, "function": new_ingredient.function, } print(data) pusher_client.trigger('table', 'new-record', {'data': data}) return redirect("/backend", code=302) else: ingredients = Ingredient.query.all() return render_template('backend.html', ingredients=ingredients)
def parseIngredients( soup ): ingredientList = [] div = soup.find('div', class_='ingredients-bl') ul = div.find('ul') li_elements = ul.find_all('li') for li in li_elements: line = li.text.replace("\n", "").replace("\r", "").replace(" ", "") lineArray = line.split('—') name = '' description = '' value = '' if "(" in str(lineArray[0]): nameDescription = lineArray[0].split('(') name = nameDescription[0] description = nameDescription[1][:-1] else: name = lineArray[0] if getSize(lineArray) > 1: value = lineArray[1] model = Ingredient(str(name), str(description), str(value)) ingredientList.append(model) return ingredientList
def create_ingredient(cuisine_id, recipe_id): recipe = session.query(Recipe).filter_by(id=recipe_id).one() print(recipe.user_id) creator = getUserInfo(recipe.user_id) if 'username' not in login_session or creator.id != login_session['id']: return redirect(url_for("showLogin")) if request.method == 'GET': state = generateAntiForgeryToken() userpicture = login_session['picture'] return render_template('createIngredient.html', STATE=login_session['state'], username=login_session['username'], recipe_id=recipe_id, picture=userpicture, cuisine_id=cuisine_id) if request.method == 'POST': print(request.form['state']) if request.form['state'] != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' flash('Invalid state parameter') return response ingredient = Ingredient(recipe_id=recipe_id, user_id=getUserId(login_session['email']), name=request.form['name'], amount=request.form['amount'], unit=request.form['unit']) session.add(ingredient) session.commit() flash('Ingredient added to recipe!') return redirect( url_for('recipe_handler', cuisine_id=cuisine_id, id=recipe_id), 303)
def post(self): form = json.loads(self.request.get('form')) name = form['name'] price = float(form['price']) * (4.0 / 3.0) # 750ml to 1L abv = int(form['abv']) ingredient = Ingredient(name=name, price=price, abv=abv) ingredient.put()
def add_ingredients_to_db(recipe_data): """ Add ingredients to the db recipe_data (obj): recipe data from the Spoonacular API with extendedIngredients - a list of ingredient objects Returns a list of SQLAlchemy ingredient objects""" ingredient_list = [] for ingredient in recipe_data['extendedIngredients']: try: db_ingredient = Ingredient.query.filter_by( id=ingredient['id']).first() if db_ingredient: ingredient_list.append(db_ingredient) else: id = ingredient.get('id', None) name = ingredient.get('name', None) original = ingredient.get('original', None) new_ingredient = Ingredient(id=id, name=name, original=original) new_ingredient = add_and_commit(new_ingredient) print(f"\n Created new ingredient {new_ingredient} \n") ingredient_list.append(new_ingredient) print(f"\n Ingredient added to list: {ingredient_list} \n") recipe_data = add_measurement_for_ingredient(ingredient, recipe_data) except Exception as e: print(str(e)) # import pdb # pdb.set_trace() db.session.rollback() continue return ingredient_list
def test_ingredient_repr_1(self): """Test __repr__ method for the class Ingredient""" name = "Rum" ingredient = Ingredient(name) ingredient_name = ingredient.__repr__() self.assertEqual("<Ingredient '%s'>" % ingredient.name, ingredient_name)
def test_ingredient_init_6(self): """Test __init__ method for the class Ingredient""" name = None image = "static/images/ingredients/Aqua.jpg" ingredient = Ingredient(name, image) self.assertIsNone(ingredient.name) self.assertIsNotNone(ingredient.image)
def test_ingredient_init_5(self): """Test __init__ method for the class Ingredient""" name = "Berries" image = "static/images/ingredients/Berries.jpg" ingredient = Ingredient(name, image) self.assertEqual(name, ingredient.name) self.assertIsNotNone(ingredient.image)
def addIngredient(): if 'email' not in session: return redirect(url_for('login')) ingForm = IngredientForm() # Temporarily passing this message object in order to display an added message under the form. message = "" if request.method == 'POST': if not ingForm.validate(): return render_template('addIngredient.html', ingForm=ingForm, message=message) else: newIng = Ingredient(ingForm.ingredientname.data) #An IntegrityError here indicates a duplicate was found. The id in the db is still #generated for some reason but the entry isn't added, so there will be skipped id's (not a problem) try: db.session.add(newIng) db.session.commit() message = "Ingredient added: " + newIng.ingredientname except exc.IntegrityError as e: db.session.rollback() ingForm.ingredientname.errors.append( "The specified Ingredient Name already exists!") finally: return render_template('addIngredient.html', ingForm=ingForm, message=message) elif request.method == 'GET': return render_template('addIngredient.html', ingForm=ingForm, message=message)
def update_recipe(jwt, recipe_id): recipe = Recipe.query.get(recipe_id) if not recipe: abort(404) data = request.get_json() # if the patch request contains ingredients, # we'll just reset the recipe's ingredients to them if 'ingredients' in data: ingredients = data.pop('ingredients') recipe.ingredients = [] for i in ingredients: ingredient = Ingredient(**i, recipe_id=recipe.id) recipe.ingredients.append(ingredient) fields = ['name', 'procedure', 'time'] has_valid_fields = any([field in data for field in fields]) if not has_valid_fields: abort(400) for field in fields: if field in data: setattr(recipe, field, data[field]) recipe.update() return jsonify({"success": True, "result": recipe.format()})
def add_quantity(id): measurements_list = Measurement.query.limit(100).all() quantity_recipe = Recipe.query.get(id) if quantity_recipe.user != current_user: flash('You do not have permission to add ingredients to this recipe') return redirect(url_for('index')) if request.method == 'POST': quantity_measurement = Measurement.query.filter_by(id=request.form['quantity_measurement']).first() # check if ingredient has already been created and if so use the existing before creating (same) new ingredient to avoid duplicate data existing_ingredient = Ingredient.query.filter_by(ingredient_name=request.form['quantity_ingredient']).first() if existing_ingredient is not None: quantity_ingredient = existing_ingredient else: quantity_ingredient = Ingredient(request.form['quantity_ingredient']) quantity = Quantity(request.form['quantity'], quantity_recipe, quantity_ingredient, quantity_measurement) db.session.add(quantity) db.session.commit() return redirect(url_for('recipe_detail', id=id)) return render_template('add_quantity.html', measurements_list=measurements_list, recipe=quantity_recipe)
def create_ingredient(jwt): try: data = request.get_json() ingredient = Ingredient(**data) ingredient.insert() return jsonify({'success': True, 'result': ingredient.format()}) except TypeError: abort(400)
def test_ingredient_repr_4(self): """Test __repr__ method for the class Ingredient""" name = "Berries" image = "static/images/ingredients/Berries.jpg" ingredient = Ingredient(name, image) ingredient_name = ingredient.__repr__() self.assertEqual("<Ingredient '%s'>" % ingredient.name, ingredient_name)
def setIngredients(recipe, param): for data in param: ingredient = Ingredient() ingredient.name = data['name'] ingredient.quantity = data['quantity'] ingredient.type = data['type'] db.session.add(ingredient) ingredient.recipe.append(recipe)
def test_ingredient(self): """ingredient Model initialization""" ing = Ingredient(name='ingredient') db.session.add(ing) db.session.commit() self.assertEqual(len(ing.cabinets), 0)
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() self.users = [] self.users.append(User()) self.users[0].name = 'Foo Bar' self.users[0].put() self.langs = [] self.langs.append(Language()) self.langs[0].name = 'English' self.langs[0].code = 'en' self.langs[0].put() self.langs.append(Language()) self.langs[1].name = 'Danish' self.langs[1].code = 'da' self.langs[1].put() self.langs.append(Language()) self.langs[2].name = 'Default (INCI)' self.langs[2].code = 'nc' self.langs[2].put() self.label_names = [] self.label_names.append(LabelName()) self.label_names[0].name = 'Vand' self.label_names[0].language = self.langs[1].key self.label_names[0].put() self.label_names.append(LabelName()) self.label_names[1].name = 'Water' self.label_names[1].language = self.langs[0].key self.label_names[1].put() self.label_names.append(LabelName()) self.label_names[2].name = 'Aqua' self.label_names[2].language = self.langs[2].key self.label_names[2].put() self.wiki_links = [] self.wiki_links.append(IngredientWikiLink()) self.wiki_links[0].ingredient = None self.wiki_links[0].link = 'http://en.wikipedia.org/wiki/water' self.wiki_links[0].is_valid = True self.wiki_links[0].creator = None self.wiki_links[0].language = None self.wiki_links[0].put() self.wiki_links.append(IngredientWikiLink()) self.wiki_links[1].ingredient = None self.wiki_links[1].link = 'http://da.wikipedia.org/wiki/vand' self.wiki_links[1].is_valid = True self.wiki_links[1].creator = None self.wiki_links[1].language = None self.wiki_links[1].put() self.ingredients = [] self.ingredients.append(Ingredient()) self.ingredients[0].put()
def test_amount_init_2(self): """Test __init__ method for the class Amount""" cocktail = Cocktail(None, None, None, None) ingredient = Ingredient(None, None) amount = "1" value = Amount(cocktail, ingredient, amount) self.assertEqual(cocktail, value.c_data) self.assertEqual(ingredient, value.i_data) self.assertEqual(amount, value.amount)
def post_ingredient(jwt): res = request.get_json() if not res: abort(404) ingredient = Ingredient(**res) ingredient.insert() result = {"success": True, "result": ingredient.format()} return jsonify(result)
def test_amount_init_1(self): """Test __init__ method for the class Amount""" cocktail = Cocktail("Moscow Mule", "Cup", "Moscow Mule Recipe") ingredient = Ingredient("Rum") amount = "2 oz." value = Amount(cocktail, ingredient, amount) self.assertEqual(cocktail, value.c_data) self.assertEqual(ingredient, value.i_data) self.assertEqual(amount, value.amount)
def test_cabinet_relationship(self): """test through relationship with Ingredient and Cabinet""" ing = Ingredient(name='ingredient') self.cab.ingredients.append(ing) db.session.commit() self.assertEqual(ing.cabinets[0], self.cab) self.assertEqual(self.cab.ingredients[0], ing)
def test_amount_init_3(self): """Test __init__ method for the class Amount""" cocktail = Cocktail("", "", "") ingredient = Ingredient("") amount = "3 oz." value = Amount(cocktail, ingredient, amount) self.assertEqual(cocktail, value.c_data) self.assertEqual(ingredient, value.i_data) self.assertEqual(amount, value.amount)
def test_amount_repr_3(self): """Test __repr__ method for the class Amount""" cocktail = Cocktail("", "", "") ingredient = Ingredient("") amount = Amount(cocktail, ingredient, "3 oz.") amount_name = amount.__repr__() self.assertEqual( "<Amount [%r-|---|-%r]>" % (amount.c_data, amount.i_data), amount_name)
def test_amount_repr_1(self): """Test __repr__ method for the class Amount""" cocktail = Cocktail("Moscow Mule", "Cup", "Moscow Mule Recipe") ingredient = Ingredient("Rum") amount = Amount(cocktail, ingredient, "2 oz.") amount_name = amount.__repr__() self.assertEqual( "<Amount [%r-|---|-%r]>" % (amount.c_data, amount.i_data), amount_name)
def test_amount_init_7(self): """Test __init__ method for the class Amount""" cocktail = Cocktail(None, None, None, None) ingredient = Ingredient(None, "static/images/ingredients/Berries.jpg") amount = "3 oz." value = Amount(cocktail, ingredient, amount) self.assertIsNotNone(value.c_data) self.assertIsNotNone(value.i_data) self.assertIsNotNone(value.amount)
def test_amount_init_5(self): """Test __init__ method for the class Amount""" cocktail = Cocktail("Aqua", "Bottle", "Aqua Recipe", "static/images/cocktails/Aqua.jpg") ingredient = Ingredient("Berries", "static/images/ingredients/Berries.jpg") amount = "3 oz." value = Amount(cocktail, ingredient, amount) self.assertIsNotNone(cocktail, value.c_data) self.assertIsNotNone(ingredient, value.i_data) self.assertIsNotNone(amount, value.amount)
def test_amount_repr_4(self): """Test __repr__ method for the class Amount""" cocktail = Cocktail("Aqua", "Bottle", "Aqua Recipe", "static/images/cocktails/Aqua.jpg") ingredient = Ingredient("Berries", "static/images/ingredients/Berries.jpg") amount = Amount(cocktail, ingredient, "3 oz.") amount_name = amount.__repr__() self.assertEqual( "<Amount [%r-|---|-%r]>" % (amount.c_data, amount.i_data), amount_name)
async def create_ingredients_from_csv(): ingredients = pandas.read_csv('ingredients.csv', header=None) print(ingredients[0].tolist()) models = [] for ingredient_name in ingredients[0].tolist(): models.append(Ingredient(name=ingredient_name)) motor = AsyncIOMotorClient(host="209.159.204.189", port=5433) engine = AIOEngine(motor_client=motor, database="Recipe") await engine.save_all(models)
async def create_ingredient(new_ingredient: Ingredient): # get all ingredients and check if a ingredient with same name exists ingredients = [] for ingredient in mongo.get_db().ingredient.find(): ingredients.append(Ingredient(**ingredient)) for ingredient in ingredients: if ingredient.name == new_ingredient.name: return {'error': 'Ingredient with same name already exists'} # if not, then save new ingredient json_compatible_data = jsonable_encoder(new_ingredient) mongo.get_db().ingredient.insert_one(json_compatible_data) return {'ingredient': new_ingredient}