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 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_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 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 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 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 add_many_ingredients_to_section(section): while True: name = raw_input('name :') if name == "": break unit = raw_input('unit :') i = Ingredient(name=name, unit=unit, is_food=True, section=section) print i.name, i.unit, 'added to', i.section i.save()
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_verify_but_not_added(self): # Sibling test to ensure that data = { # an unwanted ingredient is 'ingredient_names-0': 'sugar', # not added 'ingredient_checks-0': '', 'ingredient_names-1': 'salt', 'ingredient_checks-1': 'y' } res = self.app.post('/verify_ingredients', data=data) self.assertTrue(Ingredient.exists('salt'), 'Salt not added') self.assertFalse(Ingredient.exists('sugar'), 'Sugar were added')
def test_select_verify_new_ingredient(self): # Unit test that ensures the data = { # items are correctly added 'ingredient_names-0': 'chocolate chips', # to user Pantry if the items 'ingredient_checks-0': 'y', # are correct 'ingredient_names-1': 'flour', 'ingredient_checks-1': 'y' } res = self.app.post('/verify_ingredients', data=data) self.assertTrue(Ingredient.exists('chocolate chips'), 'Chocolate chips not added') self.assertTrue(Ingredient.exists('flour'), 'Flour not added')
def ingredient_list(self, request): ''' ingredients List ''' #retrive the requested ingredient ingredient = Ingredient.get_by_urlsafe_key(request.ingredient_key) if not ingredient: message = 'No product with the key "%s" exists.' % request.ingredient_key raise endpoints.NotFoundException(message) # retrieve the user user = User.get_by_urlsafe_key(request.user_key) if not user: message = 'No user with the key "%s" exists.' % request.user_key raise endpoints.NotFoundException(message) #Find lable name for the ingredient label_name = request.label_name if LabelName.exists(label_name): label_name = LabelName.find_by_name(label_name) else: label_name = None # retrieve the translation tanslation = Language.find_by_code(request.ingredient.language) if not language: tanslation = Language.get_unknown() #Find wiki-link for the ingredient link = request.wiki_link.link is_valid = request.wiki_link.is_valid wiki_link = None if IngredientWikiLink.exists(ingredient, tanslation): wiki_link = IngredientWikiLink.find_by_ingredient_and_language(ingredient, tanslation) wiki_link.link = link wiki_link.is_valid = is_valid wiki_link.put() else: wiki_link = None #Find Hazards for the Ingrdient hazards = HStatement.getClassifications(hazards) if not hazards: hazards = None #Find E_Number for the Ingredient e_numbers = request.e_numbers if Ingredient.e_numbers.exists(e_number): e_number = Ingredient.find_by_e_number(e_number)
def change_category(self, request): ''' Change the category of a Ingredient ''' # retrieve the requested Ingredient ingredient = Ingredient.get_by_urlsafe_key(request.ingredient_key) if not ingredient: message = 'No Ingredient with the key "%s" exists.' % request.ingredient_key raise endpoints.NotFoundException(message) # retrieve the user user = User.get_by_urlsafe_key(request.user_key) if not user: message = 'No user with the key "%s" exists.' % request.user_key raise endpoints.NotFoundException(message) # retrieve the category category = IngredientCategory.get_by_urlsafe_key(request.category_key) if not category: message = 'No category with the key "%s" exists.' % request.category_key raise endpoints.NotFoundException(message) # remove the ingredient from the old category old_category = ingredient.get_category() old_mapping = IngredientCategoryMapping.load(ingredient, old_category) if old_mapping: old_mapping.key.delete() # set the ingredient under the given category IngredientCategoryMessage.load(ingredient, category, user) # register the user as editor of the ingredient IngredientCategoryMessage.add_or_update(ingredient, user) return message_types.VoidMessage()
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 get_ingredient_name(self, request): ''' Retrieve a ingredients names ''' # get size of the name to return size = request.size # cursor state cursor = None if request.cursor: cursor = Cursor(urlsafe=request.cursor) # build the query query = Ingredient.query() names = None next_cursor = None more = False if cursor: names, next_cursor, more = query.fetch_page(size, start_cursor=cursor) else: names, next_cursor, more = query.fetch_page(size, start_cursor=cursor) if next_cursor: return IngredientHelper.create_collection(names, next_cursor.urlsafe(), more) return IngredientHelper.create_collection(names)
def post_ingredients(): """ "POST": registrar un ingrediente """ request_body = request.json if request_body is None: return jsonify({"response": "empty body"}), 400 if ("name" not in request_body or "category" not in request_body): return jsonify({"result": "missing fields in request body"}), 400 if (request_body["name"] == "" or request_body["category"] == ""): return jsonify({"response": "empty property values"}), 400 new_ingredient = Ingredient.register( request_body["name"], request_body["category"], ) db.session.add(new_ingredient) try: db.session.commit() return jsonify(new_ingredient.serializeIngredient()), 201 except Exception as error: db.session.rollback() print(f"{error.args} {type(error)}") return jsonify({"response": f"{error.args}"}), 500
def recipes_add_ingredient(): # associates an ingredient with a recipe recipe_key = request.args.get('recipe') ingredient_key = request.args.get('ingredient') recipe = Recipe.get(recipe_key) if not recipe: return json.dumps({'error': 'Recipe not found'}), 500 ingredient = Ingredient.get(ingredient_key) if not ingredient: return json.dumps({'error': 'Ingredient not found.'}), 500 if ingredient.key() in recipe.ingredients: return json.dumps({'status': 'Ingredient already in recipe.'}), 200 # if the ingredient is not already associated, associate it recipe.ingredients.append(ingredient.key()) recipe.put() # add the recipe to the ingredient's list of recipes that use it if recipe.key() not in ingredient.usedIn: ingredient.usedIn.append(recipe.key()) ingredient.put() return json.dumps( {'status': 'Associated ingredient and recipe successfully'}), 200
def add_ingredient_wiki_link(self, request): ''' Add a Wikipedia link to an ingredient of a product ''' # retrieve the user user = User.get_by_urlsafe_key(request.user_key) if not user: message = 'No user with the key "%s" exists.' % request.user_key raise endpoints.NotFoundException(message) # retrieve the ingredient ingredient = Ingredient.get_by_urlsafe_key(request.ingredient_key) if not ingredient: message = 'No ingredient with the key "%s" exists.' % request.ingredient_key raise endpoints.NotFoundException(message) # retrieve the language language = Language.find_by_code(request.language) if not language: language = Language.get_unknown() link = request.wiki_link.link is_valid = request.wiki_link.is_valid wiki_link = None if IngredientWikiLink.exists(ingredient, language): wiki_link = IngredientWikiLink.find_by_ingredient_and_language(ingredient, language) wiki_link.link = link wiki_link.is_valid = is_valid wiki_link.put() else: wiki_link = IngredientWikiLink.create(ingredient, link, language, user, is_valid) return DatastoreKeyResponse(key=wiki_link.key.urlsafe())
def map_ingredient(self, request): ''' Map an existing ingredient to a product ''' # retrieve the requested product product = Product.get_by_urlsafe_key(request.product_key) if not product: message = 'No product with the key "%s" exists.' % request.product_key raise endpoints.NotFoundException(message) # retrieve the user user = User.get_by_urlsafe_key(request.user_key) if not user: message = 'No user with the key "%s" exists.' % request.user_key raise endpoints.NotFoundException(message) # retrieve the ingredient ingredient = Ingredient.get_by_urlsafe_key(request.ingredient_key) if not ingredient: message = 'No ingredient with the key "%s" exists.' % request.ingredient_key raise endpoints.NotFoundException(message) # create the mapping mapping = ProductIngredient.add_entry(product, ingredient, user) return DatastoreKeyResponse(key=mapping.key.urlsafe())
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 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 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_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 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 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 recipes(): # get a specific recipe key = request.args.get('key') recipe = Recipe.get(key) print recipe if not recipe: return json.dumps({'error': 'Recipe not found'}), 500 recipe_object = { 'name': recipe.name, 'prepTime': recipe.prepTime, 'instructions': recipe.instructions } ingredientList = [] for i in recipe.ingredients: ing = Ingredient.get(i) ingredientList.append({ 'ing_name': ing.name, 'ing_key': str(ing.key()) }) recipe_object['ingredients'] = ingredientList return json.dumps({'status': 'OK', 'recipe': recipe_object}), 200
def put(self, key): ingredient = Ingredient.get(key) form = json.loads(self.request.get('form')) ingredient.name = form['name'] ingredient.price = float(form['price']) ingredient.abv = int(form['abv']) ingredient.put()
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(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 add_ingredient(self, request): ''' Add a new ingredient to a product ''' # retrieve the requested product product = Product.get_by_urlsafe_key(request.product_key) if not product: message = 'No product with the key "%s" exists.' % request.product_key raise endpoints.NotFoundException(message) # retrieve the user user = User.get_by_urlsafe_key(request.user_key) if not user: message = 'No user with the key "%s" exists.' % request.user_key raise endpoints.NotFoundException(message) # retrieve the language language = Language.find_by_code(request.ingredient.language) if not language: language = Language.get_unknown() # find or create the label name that is requested is_new = True name = request.ingredient.label_name label_name = None if LabelName.exists(name): label_name = LabelName.find_by_name(name) is_new = False else: label_name = LabelName.create(name, language, user) # find or create the ingredient. If it is a new ingredient, we first # create it and then map it to the label name ingredient = None if is_new: if language.is_default(): ingredient = Ingredient.create(user, name) else: ingredient = Ingredient.create(user) IngredientLabelName.create(ingredient, label_name, user) else: ingredient = IngredientLabelName.find_by_label_name(label_name).ingredient.get() # create a mapping for the ingredient and the product mapping = ProductIngredient.add_entry(product, ingredient, user) return DatastoreKeyResponse(key=mapping.key.urlsafe())
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 handleGetRequest(self): # get the recent 10 ingredients added to datastore q = Ingredient.query(ancestor=INGREDIENT_KEY) ingredients = q.order(-Ingredient.created).fetch(10) self.addTemplateValue('ingredients', ingredients) self.setActivePage('Ingredients')
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 get(self): ingredients = [] for ingredient in Ingredient.all().order('name'): ingredients.append({ 'name': ingredient.name, 'price': ingredient.price, 'abv': ingredient.abv, }) self.response.out.write(json.dumps(ingredients))
def _test_add_ingredient(self): # Input ingredients to database data = { 'ingredient': 'coffee' } res = self.app.post('/add_ingredients', data=data) ing = Ingredient.query(Ingredient.name == data['ingredient']).get() self.assertIsNotNone(ing, 'Ingredient not added')
def _test_add_duplicate_ingredient(self): # Attempt to add a same ingredient data = { # again 'ingredient': 'Tomatoes' } self.app.post('/add_ingredients', data=data) self.app.post('/add_ingredients', data=data) ingreds = Ingredient.query(Ingredient.name == data['ingredient']).fetch() self.assertEqual(len(ingreds), 1, "Duplicate ingredient added")
def get(self): q = Ingredient.all() ingredients = [i for i in q if i.quantifiedingredient_set.count() > 0] buckets,keys = bucketize(ingredients, lambda x: x.name) templatevalues = RequestContext(self.request, { 'ingredients' : ingredients, 'buckets' : buckets, 'keys' : keys }) path = os.path.join(os.path.dirname(__file__), 'ingredients_by_name.html') self.response.out.write(template.render(path, templatevalues))
def get_html(base, level): # Base case if level < 0 or base is None or not(validators.url(base)): return r = requests.get(base) soup = BeautifulSoup(r.text, 'html.parser') print base # Do any parsing on current url parent_url = url_in_rules(base) if parent_url is not None: ingredients = filter_ingredients(parent_url, soup) title = get_title_from_page(parent_url, soup) image_url = get_image_from_page(parent_url, soup) if not(title is None or image_url is None): """ Interesting thing I learned about get_or_create vs catching Exceptions: "it's easier to ask for forgiveness than for permission". """ try: recipe = Recipe(title=title, image_url=image_url, recipe_url=base) recipe.save() print "Adding recipe: {}".format(title) except IntegrityError: recipe = Recipe.objects.filter(title=title).first() for i in ingredients: try: ingredient = Ingredient(title=i,recipe=recipe) ingredient.save() print "{} to {}".format(i, recipe.title) except IntegrityError: continue # Now loop through all linked pages on the page and get their content too for link in soup.find_all('a'): page_url = link.get('href') if page_url is None or page_url == '' or page_url == '/' or page_url == base or (validators.url(page_url) and url_in_rules(page_url) != base): continue else: if url_in_rules(page_url) != base: page_url = urljoin(base, page_url) get_html(page_url, level - 1)
def test_select_add_existing_ingredient(self): # Improved version of the data = { # _test_add_duplicate_ingredient test 'ingredient_names-0': 'cookies', # that checks a repeated item 'ingredient_checks-0': 'y', # will not be added 'ingredient_names-1': 'cookies', 'ingredient_checks-1': 'y' } res = self.app.post('/verify_ingredients', data=data) cookies = Ingredient.query(Ingredient.name == 'cookies').fetch() self.assertEqual(len(cookies), 1, 'Cookies added twice!')
def get_ingredient_form(defaults=None, **kwargs): """Dynamically create the ingredients form, based on what is in the Ingredients datastore right now Returns an instance of the class, exactly as if we had called the constructor""" choices = [(x.name, x.name) for x in Ingredient.query().fetch()] class IngredientForm(Form): ingredients = MultiCheckboxField(choices=choices, default=defaults) new_ingredients = FieldList(StringField('Ingredient: '), label='Add New Ingredients', min_entries=5) def __init__(self, **kwargs): super(type(self), self).__init__(**kwargs) return IngredientForm(**kwargs)
def get(self, ingredient_key): i = Ingredient.get(ingredient_key) if i == None: # TODO: error page? return # Gather all the recipes for all the QIs for this ingredient recipes = uniq([qi.recipe for qi in i.quantifiedingredient_set], lambda x: x.title) buckets,keys = bucketize(recipes, lambda x: x.title) templatevalues = RequestContext(self.request, { 'ingredient' : i, 'recipes' : recipes, 'buckets' : buckets, 'keys' : keys }) path = os.path.join(os.path.dirname(__file__), 'recipes_by_ingredient.html') self.response.out.write(template.render(path, templatevalues))
def add_recipe(request): context = {} context['urlform'] = AddRecipebyURLForm() context['recipe'] = RecipeForm() context['instruction'] = AddInstructionsForm() context['ingredients'] = AddIngredientsForm() context['autocompleteform'] = AutocompleteSearchForm() if request.method == 'GET': return render(request, 'foodchaser/add_recipe.html', context) user = request.user recipef = RecipeForm(request.POST, request.FILES) instructionf = AddInstructionsForm(request.POST, request.FILES) ingredientsf = AddIngredientsForm(request.POST) if not recipef.is_valid() or not instructionf.is_valid() or not \ ingredientsf.is_valid(): return render(request, 'foodchaser/add_recipe.html', context) # Store ingredient ingredient = Ingredient(name = ingredientsf.cleaned_data['item']) ingredient.save() ingredientunit = IngredientUnit(quantity = ingredientsf.cleaned_data['quantity'], \ unit = ingredientsf.cleaned_data['unit'], \ notes = ingredientsf.cleaned_data['notes'], \ ingredient = ingredient) ingredientunit.save() # Store instructions step = Step(description = instructionf.cleaned_data['des'], \ preptime = instructionf.cleaned_data['preptime'], \ cooktime = instructionf.cleaned_data['cooktime'], \ picture = instructionf.cleaned_data['stepPic']) step.save() recipe = Recipe(name = recipef.cleaned_data['name'], \ description = recipef.cleaned_data['description'], \ category1 = recipef.cleaned_data['category1'], \ category2 = recipef.cleaned_data['category2'], \ spicy = recipef.cleaned_data['spicy'], \ estimated_time= recipef.cleaned_data['estimated_time'],\ owner = user,\ picture = recipef.cleaned_data['picture']) recipe.save() recipe.ingredients.add(ingredientunit) recipe.steps.add(step) # Add additional ingredients and steps # Parse additional steps i = 2 while (('des'+str(i)) in request.POST): request.POST['des'] = request.POST['des'+str(i)] request.POST['preptime'] = request.POST['preptime'+str(i)] request.POST['cooktime'] = request.POST['cooktime'+str(i)] if (('stepPic'+str(i)) in request.FILES): request.FILES['stepPic'] = request.FILES['stepPic'+str(i)] else: request.FILES['stepPic'] = None instructionf = AddInstructionsForm(request.POST, request.FILES) if not instructionf.is_valid(): return render(request, 'foodchaser/add_recipe.html', context) step = Step(description = instructionf.cleaned_data['des'], \ preptime = instructionf.cleaned_data['preptime'], \ cooktime = instructionf.cleaned_data['cooktime'], \ picture = instructionf.cleaned_data['stepPic']) step.save() recipe.steps.add(step) i += 1 # Parse additional ingredients i = 2 while (('item'+str(i)) in request.POST): request.POST['item'] = request.POST['item'+str(i)] request.POST['quantity'] = request.POST['quantity'+str(i)] request.POST['unit'] = request.POST['unit'+str(i)] request.POST['notes'] = request.POST['notes'+str(i)] ingredientsf = AddIngredientsForm(request.POST) if not ingredientsf.is_valid(): return render(request, 'foodchaser/add_recipe.html', context) # Store ingredient ingredient = Ingredient(name = ingredientsf.cleaned_data['item']) ingredient.save() ingredientunit = IngredientUnit(quantity = ingredientsf.cleaned_data['quantity'], \ unit = ingredientsf.cleaned_data['unit'], \ notes = ingredientsf.cleaned_data['notes'], \ ingredient = ingredient) ingredientunit.save() recipe.ingredients.add(ingredientunit) i += 1 recipe.save() recipes = Recipe.objects.all().filter(owner = request.user) context['recipes'] = recipes context['user'] = user return render(request, 'foodchaser/recipebox_maindish.html', context)
def save_foods(foodstuffs, types, add_beans=False, restrictions=''): for food in foodstuffs: cal = 0 if 'Energy' in food.data: cal = food.data['Energy'][0] total_fat = 0 if 'Total lipid (fat)' in food.data: total_fat = food.data['Total lipid (fat)'][0] sat_fat = 0 if 'Fatty acids, total saturated' in food.data: sat_fat = food.data['Fatty acids, total saturated'][0] mono_fat = 0 if 'Fatty acids, total monounsaturated' in food.data: mono_fat = food.data['Fatty acids, total monounsaturated'][0] poly_fat = 0 if 'Fatty acids, total polyunsaturated' in food.data: poly_fat = food.data['Fatty acids, total polyunsaturated'][0] trans_fat = 0 if 'Fatty acids, total trans' in food.data: trans_fat = food.data['Fatty acids, total trans'][0] cholesterol = 0 if 'Cholesterol' in food.data: cholesterol = food.data['Cholesterol'][0] sodium = 0 if 'Sodium, Na' in food.data: sodium = food.data['Sodium, Na'][0] potassium = 0 if 'Potassium, K' in food.data: potassium = food.data['Potassium, K'][0] carbs = 0 if 'Carbohydrate, by difference' in food.data: carbs = food.data['Carbohydrate, by difference'][0] fiber = 0 if 'Fiber, total dietary' in food.data: fiber = food.data['Fiber, total dietary'][0] sugar = 0 if 'Sugars, total' in food.data: sugar = food.data['Sugars, total'][0] protein = 0 if 'Protein' in food.data: protein = food.data['Protein'][0] vit_a = 0 if 'Vitamin A, RAE' in food.data: vit_a = food.data['Vitamin A, RAE'][0] vit_c = 0 if 'Vitamin C, total ascorbic acid' in food.data: vit_c = food.data['Vitamin C, total ascorbic acid'][0] calcium = 0 if 'Calcium, Ca' in food.data: calcium = food.data['Calcium, Ca'][0] iron = 0 if 'Iron, Fe' in food.data: iron = food.data['Iron, Fe'][0] vit_d = 0 if 'Vitamin D (D2 + D3)' in food.data: vit_d = food.data['Vitamin D (D2 + D3)'][0] vit_b_6 = 0 if 'Vitamin B-6' in food.data: vit_b = food.data['Vitamin B-6'][0] vit_b_12 = 0 if 'Vitamin B-12' in food.data: vit_b_12 = food.data['Vitamin B-12'][0] magnesium = 0 if 'Magnesium, Mg' in food.data: magnesium = food.data['Magnesium, Mg'][0] if add_beans: food.name = food.name + ' beans' new_food = Ingredient(name=food.name, modifier=food.modifier, calories=cal, total_fat=total_fat, saturated_fat=sat_fat, ingredient_type=IngredientType.objects.get(name=types),polyunsaturated_fat=poly_fat, monounsaturated_fat=mono_fat, trans_fat=trans_fat, cholesterol=cholesterol, sodium = sodium, dietary_fiber = fiber, potassium = potassium, total_carbohydrates=carbs, sugar=sugar, protein=protein, vitamin_a=vit_a, vitamin_c=vit_c, calcium=calcium, iron=iron, vitamin_d=vit_d, vitamin_b_6=vit_b_6, vitamin_b_12=vit_b_12 ,magnesium=magnesium, restrictions=restrictions) new_food.save() for unit in food.units: new_unit = ServingSize(name=unit[0], gram_conversion=unit[1], ingredients = new_food) new_unit.save()
def get(self, key): ingredient = Ingredient.get(key) return self.render('ingredient', {'ingrdient': ingredient})
def tearDown(self): for ingred in Ingredient.query().fetch(): ingred.key.delete()
def ingredient_autocomplete(): return { 'ingredients' : Ingredient.all() }
def delete(self, key): Ingredient.get(key).delete()
def test_ingredient_repr_3(self): """Test __repr__ method for the class Ingredient""" name = "" ingredient = Ingredient(name) ingredient_name = ingredient.__repr__() self.assertEqual("<Ingredient ''>", ingredient_name)
def init(request): drink1 = Drink(name='Mojito', description='Yum!', image='mojito.jpg') drink1.save() drink2 = Drink(name='Cuba Libre', description='Yuck!', image='cuba.jpg') drink2.save() i1 = Ingredient(name='Juice', description='So svalk', unit='kg') i1.save() i2 = Ingredient(name='Vatten', description='Such wet', unit='doge') i2.save() i3 = Ingredient(name='Vindruvor', description='Many rund', unit='pi') i3.save() i4 = Ingredient(name='Milk', description='Very ko', unit='mil-k') i4.save() Recipe(drink=drink1, ingredient=i1, amount=20).save() Recipe(drink=drink1, ingredient=i2, amount=20).save() Recipe(drink=drink1, ingredient=i4, amount=20, note="smaskens!").save() Recipe(drink=drink2, ingredient=i2, amount=20).save() Recipe(drink=drink2, ingredient=i4, amount=20, note="katt").save() return main(request)