def setUp(self): self.stuff = FoodStuff(name='some stuff 3') self.stuff.save() recipe = Recipe(name='some recipe 3') recipe.save() ingredient = RecipeIngredient( stuff = self.stuff, recipe = recipe, count = 1.5 ) ingredient.save() self.product = Product( name = 'some product 3', recipe = recipe, markup = 1.5 ) self.product.save() provider = FoodProvider(name='some provider') provider.save() purchase = Purchase( provider = provider, stuff = self.stuff, cost = 200, unit_count = 10, unit_size = 1, ) purchase.save() self.offer = SaleOffer(product=self.product) self.offer.save()
def setUp(self): """Create test client, add sample data.""" db.drop_all() db.create_all() Receipe_Ingredient.query.delete() User_View_Receipe.query.delete() Recipe.query.delete() Ingredient.query.delete() User.query.delete() self.client = app.test_client() u = User(email="*****@*****.**", username="******", password="******") u.id = 5555 db.session.add(u) db.session.commit() recipe = Recipe(name='Pasta and Seafood', colories=320, rating=4.5, cost=34, time_to_cook=120, image='pasta.jpg') recipe.id = 1234 db.session.add(recipe) db.session.commit()
def edit(): key = request.args.get('key') recipe = Recipe.get(key) form = RecipeForm() category = str(recipe.category) print category if request.method == 'GET': recipe = Recipe.get(key) if recipe: form.name.data = recipe.name form.under30.data = recipe.under30 # form.category.default = recipe.category # form.ingredients.data = recipe.ingredients form.instructions.data = recipe.instructions form.key = recipe.key() elif form.validate_on_submit(): recipe.name = form.name.data recipe.under30 = form.under30.data recipe.category = form.category.data recipe.ingredients = form.ingredients.data recipe.instructions = form.instructions.data recipe.put() print "Recipe edited." time.sleep(1) return redirect('/all') return render_template('edit_recipes.html', recipe=recipe, form=form, category=category)
def results(page_num): RESULTS_PER_PAGE = 12 results = [] if 'id_list' in session: id_list = session['id_list'] else: return render_template('search_results.html', results=None, total_pages=0, cur_page=0) total_pages = math.ceil(len(id_list) / RESULTS_PER_PAGE) - 1 recipe_lengths = Recipe.return_recipe_lengths(id_list) recipe_lengths.sort(key=lambda x: x[1]) index_start = page_num * RESULTS_PER_PAGE if index_start >= len(recipe_lengths): flash("Out of search results index") return render_template('404.html') for index in range(index_start, index_start + RESULTS_PER_PAGE): if index < len(recipe_lengths): results.append( Recipe.get_full_recipe_from_id(recipe_lengths[index][0])) else: break return render_template('search_results.html', results=results, total_pages=total_pages, cur_page=page_num)
def create_recipe(): data = request.get_json() recipe = data.get("recipe") owner = data.get("owner") user = AppUser.query.filter(AppUser.name == owner).first() if user is None: user = AppUser(name=owner) try: user.insert() except: abort(422) title = recipe.get("recipeTitle") ingredients = json.dumps(recipe.get("ingredients", "")) instructions = recipe.get("instructions") recipe = Recipe(title=title, ingredients=ingredients, instructions=instructions, owner_id=user.id) try: recipe.insert() except: abort(422) return jsonify({ "success": True, "recipe": recipe.long(), })
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 create_recipe(user): try: id = user['user']['id'] body = request.form.to_dict() #validar los inputs de la receta title ingredients y elaboration if request.form.get('title')=='': return jsonify("Title cannot be empty"),400 if request.form.get('ingredients')=='' : return jsonify("Ingredients cannot be empty"),400 if request.form.get('elaboration')=='' : return jsonify("Elaboration cannot be empty"),400 if request.files['image']=='': return jsonify("Image cannot be empty"),400 new_file = request.files['image'] url_image = validate_file_format(app, new_file) new_recipe = Recipe(title = body['title'], image = url_image,ingredients = body['ingredients'], elaboration = body['elaboration'], user_id = id) db.session.add(new_recipe) db.session.commit() #Buscamos cada categoría en la base de datos y la añadimos a recipe category allCategories = json.loads(body["categories"]) for category in allCategories: thisCategory = Category.query.filter_by(name_category = category).first() if thisCategory: new_recipe_category = Recipe_Category(id_category = thisCategory.id, id_recipe = new_recipe.id) db.session.add(new_recipe_category) db.session.commit() return jsonify(new_recipe.serialize()),200 except OSError as error: return jsonify("error" +str(error)), 400 except KeyError as error_key: return jsonify("error_key" + str(error_key)), 400
def add_recipe(): if request.query_string[:4] == "url=": app.logger.info("Adding from source: " + request.query_string[4:]) form = fillout_form( request.query_string[4:] ) else: form = RecipeForm(request.form) if request.method == "POST": if form.validate_on_submit(): app.logger.info("Adding a new Recipe") recipe=Recipe() form.populate_obj(recipe) if len(request.files) > 0: app.logger.debug("Image uploaded") req = request filename = req.files['image_file'].filename recipe_name = recipe.recipe_name recipe.image_path = upload_image(req, filename, recipe_name) if recipe.image_path is None: flash("Error uploading image") recipe.user_id = 1 recipe.timestamp = date.today() db.session.add(recipe) db.session.commit() new_rec = Recipe.query.filter(Recipe.recipe_name== str(recipe.recipe_name)).first() #import pdb; pdb.set_trace() return redirect(url_for('view_recipe', id=new_rec.id)) else: flash('Invalid data') return render_template('recipe_form.html',form = form, title="Add A New Recipe") elif request.method != "POST": return render_template('recipe_form.html',form = form, title="Add A New Recipe") return redirect(url_for('add_recipe'))
def run_query(first_line, second_line, third_line, pic_url): recipe = Recipe(line1=first_line, line2=second_line, line3=third_line, image_url=pic_url) recipe_key = recipe.put() print("&&&&&&&&&&&&&&&&&&&&&&&&&") print recipe_key
def post(self): if not users.is_current_user_admin(): return self.redirect(users.create_login_url(self.request.url)) key = self.request.get('key') logging.debug("Deleting recipe " + key) Recipe.get(key).delete() self.redirect('/')
def create_recipe(): if not request.json: abort(404) recipe = Recipe() db.session.add(recipe) recipe.load(request.json) db.session.commit() return jsonify(message={"recipe": recipe.serialize}), 201
def remove_recipe(recipe_id): """Remove individual recipe from saved recipes""" if not g.user: flash('Please login to save/remove recipes', "danger") return redirect('/') Recipe.delete_recipe(recipe_id) db.session.commit() flash('Your recipe was removed!', category='success') return redirect(f'/users/{g.user.id}/favorites')
def fixtures_data(): # milch = Ingredient(name="Milch", quantity=0.5, unit="l") # senf = Ingredient(name="Senf", quantity=2, unit="tsp") eier_mit_senf = Recipe(name="Eier mit Senfsauce", ingredients=[{ 'foo': 'bar' }]) eier_mit_senf.save() return True
def generateRecipeData(): with open('static/recipes.json') as file: data = json.load(file) for val in data: recipe = Recipe() recipe.recipe_name = val['name'] setIngredients(recipe, val['ingredients']) setRecipeSteps(recipe, val['steps']) recipe.imageURL = val['imageURL'] recipe.originalURL = val['originURL'] db.session.commit()
def setUp(self): stuff = FoodStuff(name='some stuff 2') stuff.save() recipe = Recipe(name='some recipe 2') recipe.save() ingredient = RecipeIngredient(stuff=stuff, recipe=recipe, count=1.5) ingredient.save() self.product = Product(name='some product 2', recipe=recipe) self.product.save()
def post(self): if not users.is_current_user_admin(): return self.redirect('/') # Extract values from json json = simplejson.loads(self.request.get('json')) # Create a recipe therecipe = Recipe() therecipe.set_from_dict(json) self.redirect('/recipe/%s' % therecipe.key())
def recipe_new(): error = None if request.method == 'POST': recipe = Recipe(request.form) recipe.save() #if recipe.save(): return redirect(url_for('recipe_show', id=recipe.id)) else: recipe = Recipe() # request was GET return render_template('recipes/edit.html', recipe=recipe, error=error)
def create_recipe(token): error = 422 try: if request.data: body = request.get_json() new_name = body.get('name') new_time_to_prepare = body.get('time_to_prepare') new_cooking_time = body.get('cooking_time') new_description = body.get('description') new_item_list = body.get('item_list') if len(new_item_list) == 0: eror = 422 abort(error) new_recipe = Recipe( name=new_name, time_to_prepare=new_time_to_prepare, cooking_time=new_cooking_time, description=new_description, ) new_recipe.insert() for item in new_item_list: new_recipeItem = RecipeItem(recipe_id=new_recipe.id, item_id=item["item_id"], mesuare_id=item["mesuare_id"], count=item["count"]) db.session.add(new_recipeItem) db.session.commit() '''Pagination''' selection = Recipe.query.all() current_recipes = paginate_recipes(request, selection) '''error 404. if there isn't any recipes on the page''' if len(current_recipes) == 0: error = 404 abort(error) return jsonify({ "success": True, "created": new_recipe.id, "recipes": current_recipes }), 200 except Exception: db.session.rollback() abort(error) finally: db.session.close()
def test_delete_recipe(self): res = Recipe(title="Rice and Peas", recipe_source_url=None, recipe_source_id=112, recipe_image=None, likes=30, rating=100, summary="This is the recipe summary") r_id = 111 res.id = r_id db.session.add(res) db.session.commit() new_res = Recipe.delete_recipe(112) self.assertEqual(new_res, 112)
def test_str(self): stuff = FoodStuff(name='some stuff') stuff.save() recipe = Recipe(name='some recipe') recipe.save() ingredient = RecipeIngredient( stuff = stuff, recipe = recipe, count = 1.5 ) ingredient.save() self.assertEqual('some stuff x 1.5', str(ingredient))
def _process_raw_json_data(self, req_data): """ Handles processing of records incase the recipe data is being submitted as a raw JSON string @req_data: The request payload object """ user_token = request.headers.get('Authorization').split(sep=' ')[-1] user_id = self._get_user_id_from_token(user_token) title = req_data.get('title') description = req_data.get('description') fulfilled = req_data.get('fulfilled') # Check for required fields if title is None or len(title) == 0: # Nonexistant or empty abort(400, 'Please attach a user to this recipe') # Check if recipe owner exists existant_user = User.query.filter_by(id=user_id).first() if existant_user is None: print('Recipe owner does not exist!') res = jsonify({'status': 400}) abort(res) # Check if recipe owner is originator of request req_token = BaseController.get_auth_token(request) token_owner = User.query.filter_by(auth_token=req_token).first() if user_id != token_owner.id: abort(400, 'Recipe owner/Token owner mismatch') try: new_recipe = Recipe(user_id=existant_user.id, title=title, description=description, fulfilled=fulfilled) new_recipe.save() except IntegrityError: abort(400, 'Possibly duplicate recipe!') # TODO: Set 201 in header and return created item, like github does it saved_recipe = Recipe.query.filter_by(title=title).first() result = { 'id': saved_recipe.id, 'user_id': saved_recipe.user_id, 'title': saved_recipe.title, 'description': saved_recipe.description, 'fulfilled': saved_recipe.fulfilled, 'created': saved_recipe.created.strftime('%Y-%m-%d %H:%M:%S'), 'modified': saved_recipe.modified, } return result
def add_recipe(recipe): """Add recipe to favorites tables in the DB""" id = recipe.get('id', None) title = recipe.get('title', None) image = recipe.get('image', None) sourceName = recipe.get('sourceName', None) sourceUrl = recipe.get('sourceUrl', None) readyInMinutes = recipe.get('readyInMinutes', None) servings = recipe.get('servings', None) favorite_recipe = Recipe(id=id, title=title, image=image, sourceName=sourceName, sourceUrl=sourceUrl, readyInMinutes=readyInMinutes, servings=servings) try: db.session.add(favorite_recipe) db.session.commit() except Exception: db.session.rollback() print("THIS IS AN EXCEPTION", str(Exception)) return "ERROR OCCURED IN SAVING RECIPE, PLEASE TRY AGAIN", str( Exception) return favorite_recipe
def submit(request): recipe_form = SubmitRecipeForm() image_form = SubmitRimageForm() submitted = False if request.method == 'POST': name = request.POST.get('name') steps=request.POST.get('steps') ingredients=request.POST.get('ingredients') image= request.POST.get('image') obj= Recipe(name=name,steps=steps,ingredients=ingredients) obj.save() obj1 = Image(name=obj,image=image) obj1.save() submitted = True return render(request, 'submit-form.html', {'recipe_form':recipe_form,'image_form':image_form,'submitted':submitted } )
def add(): key = request.args.get('key') print 'deleting key %s' % key recipe = Recipe.get(key) recipe.delete() time.sleep(1) return redirect('/all')
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 get_search_results(): formdata = request.form['q'] req_data = requests.get( f'{SPOON_API}/recipes/autocomplete?query={formdata}&apiKey={API_KEY}' ).json() all_recipe_ids = "" for result in req_data: r_id = result['id'] if (db.session.query(Recipe.id).filter_by(id=r_id).scalar() is None): recipe = Recipe(id=r_id) db.session.add(recipe) all_recipe_ids += f'{r_id},' db.session.commit() if not all_recipe_ids: no_results = "No results found!" return render_template('search.html', no_results=no_results) all_results = requests.get( f"{SPOON_API}/recipes/informationBulk?ids={all_recipe_ids}&apiKey={API_KEY}" ).json() likes = [] for like in g.user.likes: likes.append(like.id) return render_template('search.html', all_results=all_results, likes=likes)
async def is_cocktail_mixable(name: str): recipeExists = False # get all recipes and check if a recipe with this name exists recipes = [] for recipe in mongo.get_db().recipe.find(): recipes.append(Recipe(**recipe)) for recipe in recipes: if recipe.name == name: recipeExists = True if recipeExists is False: raise HTTPException(status_code=404, detail='Error: This Recipe does not exist') # check if cocktail is mixable mixable = False ingredient_ids = get_ingredient_ids(name) # check for every ingredient by its id if dispenser is not -1 for ingredient_id in ingredient_ids: # if one dispenser value of an ingredient is -1 set mixable false and break the loop if mongo.get_db().ingredient.find({ "$and": [{ "_id": ObjectId(ingredient_id) }, { "dispenser": -1 }] }).count() > 0: mixable = False break else: mixable = True return {'data': mixable}
def add_recipe_to_db(recipe_data): """Add a recipe to the db recipe_data (obj): recipe data from the Spoonacular API Returns the recipe from the db""" id = recipe_data.get('id', None) title = recipe_data.get('title', None) image = recipe_data.get('image', None) sourceName = recipe_data.get('sourceName', None) sourceUrl = recipe_data.get('sourceUrl', None) readyInMinutes = recipe_data.get('readyInMinutes', None) servings = recipe_data.get('servings', None) instructions = recipe_data.get('instructions', None) vegetarian = recipe_data.get('vegetarian', None) vegan = recipe_data.get('vegan', None) glutenFree = recipe_data.get('glutenFree', None) dairyFree = recipe_data.get('dairyFree', None) sustainable = recipe_data.get('sustainable', None) ketogenic = recipe_data.get('ketogenic', None) recipe = Recipe(id=id, title=title, image=image, sourceName=sourceName, sourceUrl=sourceUrl, readyInMinutes=readyInMinutes, servings=servings, instructions=instructions, vegetarian=vegetarian, vegan=vegan, glutenFree=glutenFree, dairyFree=dairyFree, sustainable=sustainable, ketogenic=ketogenic) try: recipe = add_and_commit(recipe) except Exception: db.session.rollback() print(str(Exception)) return "Recipe couldn't be saved. Please try again." ingredients = add_ingredients_to_db(recipe_data) for ingredient in ingredients: recipe.ingredients.append(ingredient) db.session.commit() return recipe
def setUp(self): """Create test client, add sample data.""" db.drop_all() db.create_all() user1 = User.signup(username="******", first_name="first1", last_name="last1", email="*****@*****.**", password="******") user1.id = 1000 user1_id = user1.id db.session.commit() new_recipe = Recipe( recipe_id=2000, title="Roast Chicken", image= "https://www.recipetineats.com/wp-content/uploads/2020/02/Honey-Garlic-Chicken-Breast_5-SQ.jpg" ) db.session.add(new_recipe) db.session.commit() self.user1 = User.query.get(user1_id)
def recipe_delete(id): recipe = Recipe.find(id) if recipe is None: abort(404) recipe.destroy() return redirect(url_for('recipe_index'))
def setUp(self): """create test client, and add sample data""" User.query.delete() Cabinet.query.delete() Recipe.query.delete() Follows.query.delete() Favorites.query.delete() Comment.query.delete() Post.query.delete() Ingredient.query.delete() db.session.commit() self.client = app.test_client() self.u = User.signup( username='******', email='*****@*****.**', password='******', ) db.session.add(self.u) db.session.commit() self.rec = Recipe(name='Recipe') db.session.add(self.rec) db.session.commit()
def getRecipe(data, ownerId): title = data[TITLE_ID] desc = data[DESCRIPTION_ID] calories = data[CALORIES_ID] video = data[VIDEO_ID] recipe = Recipe(ownerId, title, desc, calories, video) return recipe
def post(self): recipeTemplate = theJinjaEnvironment.get_template( 'templates/recipe.html') recipeName = self.request.get("recipeName") recipesDatabase = Recipe.query().fetch() recipe = None for i in range(len(recipesDatabase)): if (recipesDatabase[i].title == recipeName): recipe = recipesDatabase[i] allergyName = self.request.get("allergyName") templateDict = { "allergyName": allergyName, "title": recipe.title, "allergenFree": recipe.allergenFree, "otherTags": recipe.otherTags, "basicIngredients": recipe.basicIngredients, "ingredients": recipe.ingredients, "steps": recipe.steps, } self.response.write(recipeTemplate.render(templateDict))
async def get_recipe_by_name(name: str): req = mongo.get_db().recipe.find_one({"name": name}) if req is None: raise HTTPException(status_code=404, detail="Error: Recipe not found") recipe = Recipe(**req) return {'data': recipe}
def get_ingredients(name): recipe = Recipe(**mongo.get_db().recipe.find_one({"name": name})) ingredients = [] # add all ingredient ids in a list for ingredient in recipe.ingredients: ingredients.append(ingredient) return ingredients
def process_Recipe(name, image, user, response): """Converts data to whole numbers and returns Recipe model""" calories = round(response['calories']) if response['calories'] else 0 carbs = round(response['totalNutrients']['CHOCDF']['quantity']) fat = round(response['totalNutrients']['FAT']['quantity']) protein = round(response['totalNutrients']['PROCNT']['quantity']) fiber = round(response['totalNutrients']['FIBTG']['quantity']) carbs_from = round( response['totalNutrientsKCal']['CHOCDF_KCAL']['quantity']) fat_from = round( response['totalNutrientsKCal']['FAT_KCAL']['quantity']) protein_from = round( response['totalNutrientsKCal']['PROCNT_KCAL']['quantity']) recipe_img = image or Recipe.recipe_image.default.arg return Recipe(name=name, calories=calories, recipe_image=recipe_img, carbs=carbs, fat=fat, protein=protein, fiber=fiber, carbs_from=carbs_from, protein_from=protein_from, fat_from=fat_from, user_id=user.id)
def addRecipe(): if 'email' not in session: return redirect(url_for('login')) recForm = AddArticleForm() # Temporarily passing this message object in order to display an added message under the form. message = "" if request.method == 'POST': if not recForm.validate(): return render_template('newrecipe.html', recForm=recForm, message=message) else: # The Recipe constructor adds each ingredient in this tuple as a child which handles the many-to-many relationship ingredients = recForm.recipeingredients.data newRec = Recipe(recForm.recipetitle.data, recForm.recipedesc.data, ingredients, session['email']) # No Try/Catch here because the db is not configured to require unique titles db.session.add(newRec) db.session.commit() message = "Recipe added: " + newRec.recipetitle return redirect(url_for('index')) elif request.method == 'GET': return render_template('newrecipe.html', recForm=recForm, message=message)
def createRecipe(): # GET route delivers a form to create a new recipe, seeding it with state # variable if request.method == 'GET': if 'username' not in login_session: return redirect(url_for('showLogin')) state = login_session['state'] print(get_flashed_messages()) return render_template('newrecipe.html', username=login_session['username'], STATE=login_session['state']) # POST route checks that state variable received from that form is # correct, creates recipe in database and redirects to create ingredient # page if request.method == 'POST': if request.form['state'] != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response newRecipe = Recipe(name=request.form['name'], description=request.form['description'], difficulty=request.form['difficulty'], cuisine_id=request.form['cuisine'], user_id=getUserId(login_session['email'])) session.add(newRecipe) session.commit() flash("recipe successfully created!") return redirect( url_for('create_ingredient', cuisine_id=newRecipe.cuisine_id, recipe_id=newRecipe.id))
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 calc_recipes(): paginate=25 recipecount = Recipe.select().count() if recipecount>paginate: pagecount = ceil(recipecount/float(paginate)) else: pagecount=1 return pagecount, paginate
def get(self, month): if month.capitalize() in seasons().keys(): recipes = uniq([k for k in queryForMonth(seasons()[month][0])] + [k for k in queryForMonth(seasons()[month][1])] + [k for k in queryForMonth(seasons()[month][2])]) recipes = [Recipe.get(k) for k in recipes] else: recipes = [r for r in Recipe.gql('WHERE %s = TRUE' % month.lower())] templatevalues = RequestContext(self.request, { 'month' : month.capitalize(), 'recipes' : recipes, 'json' : simplejson.dumps([r.to_dict() for r in recipes]), }) path = os.path.join(os.path.dirname(__file__), 'month.html') self.response.out.write(template.render(path, templatevalues))
def create(self, request, **kwargs): """ Creates a cookbook db object from a remote url :param request: dict with request values :param kwargs: additional arguments :return: json response with operation status """ # Check data validity if 'upload_url' in request.data.keys(): url = request.data['upload_url'] user = request.user.username LOG.info("Creating Cookbook from %s" % url) else: return Response({'detail': 'Insufficient payload'}, status=status.HTTP_400_BAD_REQUEST) # Download contents to temporary local storage # TODO: better github quota management name, path = LocalStorage().download(url) if not name: return Response('Error downloading %s. Quota exceeded?' % url, status=status.HTTP_400_BAD_REQUEST) # Parse downloaded contents system = LocalStorage().find_system(path) if not system: return Response({'detail': 'No valid cookbook detected for %s' % url}, status=status.HTTP_400_BAD_REQUEST) # Add valid cookbook to user repo m = RepoManager(user) cb_path, version = m.add_cookbook(path) # Generate valid cookbook try: cb = CookBook.objects.get(name=name, user=user) LOG.info("Updating Cookbook {} for user {}".format(name, request.user.id)) # Remove old recipes Recipe.objects.filter(cookbook=cb).delete() except CookBook.DoesNotExist: LOG.info("Generating Cookbook {} for user {}".format(name, request.user.id)) cb = CookBook(user=user, name=name, path=cb_path, version=version, system=system) cb.save() for r in LocalStorage().list_recipes(cb.path): ro = Recipe() ro.name = r ro.cookbook = cb ro.version = RepoManager(user).browse_file(r) ro.system = system ro.user = user ro.save() cbs = CookBookSerializer(cb) resp = Response(cbs.data, status=status.HTTP_201_CREATED) return resp
def get(self): q = Recipe.all() templatevalues = RequestContext(self.request, { 'recipes' : [r for r in q if len(r.tags) == 0] }) path = os.path.join(os.path.dirname(__file__), 'no_tags.html') self.response.out.write(template.render(path, templatevalues))
def post(self): data = json.loads(request.data) user = g.user recipe = Recipe() recipe.name = data["name"] for ingredient in data["ingredients"]: irec = RecipeIngredient() irec.name = ingredient recipe.ingredients.append(irec) recipe.instructions = data["instructions"] recipe.author = data["author"] user.recipes.append(recipe) #db.session.add(recipe) try: db.session.commit() except Exception,e: print "error adding new record" db.session.rollback()
def post(self, recipe_key): recipe = Recipe.get(recipe_key) if users.is_current_user_admin() and recipe != None: sticky = Sticky() sticky.recipe = recipe sticky.text = self.request.get('text') sticky.put() self.response.headers['Content-Type'] = 'text/javascript' self.response.out.write(simplejson.dumps(sticky.to_dict()))
def setUp(self): self.stuff = FoodStuff(name='some stuff 4') self.stuff.save() recipe = Recipe(name='some recipe 4') recipe.save() self.ingredient = RecipeIngredient( stuff = self.stuff, recipe = recipe, count = 1.5 ) self.ingredient.save() self.product = Product(name='some product 4', recipe=recipe) self.product.save() self.offer = SaleOffer(product=self.product) self.offer.save()
def get(self): item = None if self.request.get('key'): item = Recipe.get( self.request.get('key') ) vals = { 'item' : item, 'sections' : Section.all(), 'types' : models.type_choices } self.template( 'recipe-form.html', vals, 'admin' );
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 get(self): have = [] havenot = [] for r in Recipe.all(): if r.stickies.count(1) > 0: have.append(r) else: havenot.append(r) templatevalues = RequestContext(self.request, { 'have' : have, 'havenot' : havenot, }) path = os.path.join(os.path.dirname(__file__), 'recipes_by_sticky.html') self.response.out.write(template.render(path, templatevalues))
def get(self): q = Recipe.all() recipes = [r for r in q] buckets,keys = bucketize(recipes, lambda x: x.title) templatevalues = RequestContext(self.request, { 'recipes' : recipes, 'buckets' : buckets, 'keys' : keys, }) path = os.path.join(os.path.dirname(__file__), 'recipes_by_title.html') self.response.out.write(template.render(path, templatevalues))
def recipe_edit(id): error = None recipe = Recipe.find(id) if request.method == 'POST': #if recipe.update(request.form): recipe.update(request.form) recipe.save() return redirect(url_for('recipe_show', id=recipe.id)) # request was GET return render_template('recipes/edit.html', recipe=recipe, error=error)
def get(self): whereclause = ' AND '.join(['%s = FALSE' % m.lower() for m in allmonths()]) logging.debug(whereclause) q = Recipe.gql('WHERE ' + whereclause) templatevalues = RequestContext(self.request, { 'recipes' : [r for r in q] }) path = os.path.join(os.path.dirname(__file__), 'no_season.html') self.response.out.write(template.render(path, templatevalues))
def get(self): try: if self.request.get('key'): item = Recipe.get( self.request.get('key') ) vals = { 'item' : item, } self.template( 'recipe-del.html', vals, 'admin' ); else: self.redirect('.') except: self.redirect('.')
def show_recipes(page=1): pagecount, perpage=calc_recipes() recipes = Recipe.select().order_by(Recipe.title).paginate(int(page), perpage) page=int(page) if page>1: recipes.newer=page-1 else: recipes.newer=None if pagecount>page: recipes.older=page+1 else: recipes.older=None return render_template('show_recipes.html', recipes=recipes)
def get(self): section = None if self.request.get('section'): try: section = Section.get( self.request.get('section') ) except BadKeyError: # invalid key self.redirect('.') recipes = Recipe.all().filter('section =', section).order('-inserted').fetch(page_count+1) else: recipes = Recipe.all().order('-inserted').fetch(page_count+1) more = True if len(recipes) > page_count else False vals = { 'title' : 'Recipe List', 'sections' : Section.all(), 'section' : section, 'recipes' : recipes, 'page_count' : page_count if more else len(recipes), 'more' : more, } self.template( 'recipe-list.html', vals, 'admin' );
def post(self): try: item = Recipe.get( self.request.get('key') ) if self.request.get('key') else None if item is not None: try: item.delete() self.redirect('.') except: vals = { 'item' : item, 'err' : 'There was an error when deleting this recipe, please try again' } self.template( 'recipe-del.html', vals, 'admin' ); except: self.redirect('.')
def add_recipe(): form = RecipeForm() if request.method == 'POST' and form.validate(): # Add recipe to database and create ingredient links recipe = Recipe(name=form.name.data, type=form.type.data, time=form.time.data, category=form.category.data, serves=form.serves.data, method=form.method.data) db.session.add(recipe) # Create links between recipe and all ingredients required for ingredient in session['ingredients']: find_ingredient = Ingredient.query.filter_by(name=ingredient[0]).first() ing_recipe_link = RI_Link(r_id=recipe.id, i_id=find_ingredient.id, quantity=ingredient[1], q_type=ingredient[2]) recipe.ingredients.append(ing_recipe_link) find_ingredient.recipes.append(ing_recipe_link) # Add calorie value for the recipe calories = 0 for ingredient in session['ingredients']: find_ing = Ingredient.query.filter_by(name=ingredient[0]).first() if ingredient[2] == 'g': calories += int(ingredient[1])*int(find_ing.calories_per_g) elif ingredient[2] == 'mL': calories += int(ingredient[1])*int(find_ing.calories_per_ml) elif ingredient[2] == 'tbs': calories += int(ingredient[1])*int(find_ing.calories_per_tbs) elif ingredient[2] == 'tsp': calories += int(ingredient[1])*int(find_ing.calories_per_tsp) elif ingredient[2] == 'each': calories += int(ingredient[1])*int(find_ing.calories_per_each) recipe.calories = int(calories/(int(recipe.serves))) db.session.commit() return redirect(url_for('index')) session['ingredients'] = [] session.modified = True form = RecipeForm() return render_template('add-recipe.html', title= 'Add Recipe', form = form)
def post(self, key): if not users.is_current_user_admin(): return self.redirect('/') # Extract values from json json = simplejson.loads(self.request.get('json')) # Get the recipe r = Recipe.get(json['key']) if r == None: return self.redirect('/') # Set the new values r.set_from_dict(json) self.redirect("/recipe/" + str(r.key()))
def get(self): q = Query(Recipe, True) i = random.randint(0,q.count()-1) recipe = Recipe.get(q[i]) if recipe == None: # TODO: error page? return recipe_dict = recipe.to_dict() templatevalues = RequestContext(self.request, { 'recipe' : recipe, 'json' : simplejson.dumps(recipe_dict), }) path = os.path.join(os.path.dirname(__file__), 'randomrecipe.html') self.response.out.write(template.render(path, templatevalues))