def create_recipe(data): try: recipe_schema = RecipeSchema() data['id'] = str(uuid.uuid4()) validated_data = recipe_schema.load(data) new_recipe = Recipe(**validated_data) db.session.add(new_recipe) db.session.commit() return recipe_schema.dump(new_recipe), None except ValidationError: log.debug('invalid recipe data' ) # ToDo: reenviar msg asignados en la validación traceback.print_exc() return None, { 'msg': 'there was an error validating recipe', 'status_code': 400 } except SQLAlchemyError: log.error('there was a databaser error while creating recipe') traceback.print_exc() return None, { 'msg': 'there was an error creating recipe', 'status_code': 500 }
def search(params: 'SearchQueryParam'): # ToDo: la respuesta del search cambia dependiendo de los parámetros (lista vs paginación) revisar si mover esto (?) if params.ids is not None: recipes, error = multiget(params.ids, params.fields) return jsonify(recipes), error # note that this jsonify is necessary try: result = Recipe.search(params) res = { 'paging': { 'offset': params.offset, 'limit': params.limit }, 'results': result.items } paginated_response = RecipePaginationSchema().dump(res) return paginated_response, None except SQLAlchemyError as e: log.error( f'there was a database error while searching recipes(s) [error:{str(e)}]' ) traceback.print_exc() return None, { 'msg': 'there was an error searching recipes(s)', 'status_code': 500 }
def update_recipe(recipe_id: str, data: dict): try: recipe_schema = RecipeSchema() validated_data = recipe_schema.load(data, partial=True) recipe = Recipe.get_by_id(recipe_id) for attribute in validated_data: setattr(recipe, attribute, validated_data[attribute]) db.session.add(recipe) db.session.commit() return recipe_schema.dump(recipe), None except ValidationError: log.error( f'there was an error while parsing data for recipe update [id:{recipe_id}]' ) traceback.print_exc() return None, {'msg': 'invalid data for recipe', 'status_code': 400} except SQLAlchemyError: log.error( f'there was a database error while updating recipe [id:{recipe_id}]' ) traceback.print_exc() return None, { 'msg': 'there was an error while updating recipe', 'status_code': 500 }
def show(self, id): self.editing_id = int(request.args.get("editing_id", 0)) self.public_recipes = Recipe.load_all_public(exclude_mine=True) self.daily_recipes = self.daily_plan.daily_recipes self.daily_recipes.sort(key=lambda x: x.order_index) return self.template()
def comment(): if request.method == "POST": # create recipe dictionary from form data comment = { "_id": request.form['_id'], "title": request.form['title'], "username": request.form['username'], "date": request.form['date'], "reply": request.form['reply'] } # add comment to recipe comments list Recipe.add_comment(request.form['_id'], comment) return "Comment Added"
def profile(): # get users recipes recipes = Recipe.get_user_recipes() # get graphs likes_chart = Graphs.likes_chart() kcal_chart = Graphs.kcal_chart() return render_template('profile.html', recipes=recipes, likes_chart=likes_chart, kcal_chart=kcal_chart)
def load_all_in_public_recipes(ordered=True) -> list: from app.models.recipes import Recipe from app.helpers.general import list_without_duplicated ingredients = [x.ingredients for x in Recipe.load_all_public()] # flatten ingredients = [y for x in ingredients for y in x] ingredients = list_without_duplicated(ingredients) if ordered: ingredients.sort(key=lambda x: unidecode(x.name.lower())) return ingredients
def multiget(ids: list, fields: list): try: ingredients = Recipe.multiget(ids, fields) except Exception as e: log.error( 'there was a database error while performing multiget on recipes [ids:%s][error:%s]', ','.join(ids), str(e)) return None, { 'msg': 'there was an error getting ingredients', 'status_code': 500 } return RecipeSchema(many=True).dump(ingredients), None
def get_recipe_by_id(recipe_id: str, params: 'SearchQueryParam'): try: recipe = Recipe.get_by_id(recipe_id, params.fields) return RecipeSchema().dump(recipe), None except SQLAlchemyError: log.error( f'there was a database error while getting recipe by id [recipe_id:{recipe_id}]' ) traceback.print_exc() return None, { 'msg': 'there was an error getting recipe', 'status_code': 500 }
def categories(category, data): # set default arguments for page and sort order # if an argument cannot be found it must be the first page sort = request.args.get('sort') or 'users.likes' order = request.args.get('order') or -1 page = request.args.get('page') or 1 # get recipes data by category recipes = Recipe.get_by_category(category, data, sort, int(order), int(page), num=12) # pagination variables pages = ceil(recipes[2] / 12) + 1 page = int(page) start = page end = pages # pagination logic if pages <= 5: start = 1 else: if page <= 3: start = 1 end = 6 elif page > 3 and page < (pages - 2): start = page - 2 end = page + 3 else: start = pages - 5 # render template return render_template( 'categories.html', category=category, data=data, sort=sort, num=12, page=int(page), pages=pages, recipes=recipes[0], slideshow=recipes[1], count=recipes[2], start=start, end=end )
def filters(): # create default sorting options recipe_filters = {} options = {'sort': 'users.likes', 'order': -1, 'limit': 12} # get search term if it exists search_term = request.args.get('search_term') if request.method == 'POST': recipe_filters = request.form.to_dict() if recipe_filters['limit']: sort_values = recipe_filters['sort'].split(',') options['sort'] = sort_values[0] options['order'] = sort_values[1] options['limit'] = recipe_filters['limit'] del recipe_filters['sort'] del recipe_filters['limit'] # filter recipes and return results to the same page filtered_recipes = Recipe.get_filtered_recipes(recipe_filters, options=options, search_term=search_term) return render_template('filters.html', recipes=filtered_recipes, search_term=search_term, sort=options['sort'])
def get_recipe_with_ingredients(recipe_id, params): try: recipe = Recipe.get_by_id(recipe_id, params.fields) except SQLAlchemyError: log.error( f'there was a database error while looking recipe with ingredients [recipe:{recipe_id}]' ) traceback.print_exc() return None, { 'msg': 'there was and error while looking for recipe ingredients', 'status_code': 500 } if recipe is None: return None, { 'msg': f'recipe with \'id\' {recipe_id} does not exits', 'status_code': 404 } try: ingredients = RecipeIngredient.get_ingredients(recipe_id) except SQLAlchemyError: log.error( f'there was a database error while looking ingredients for recipe with ingredients [recipe:{recipe_id}]' ) traceback.print_exc() return None, { 'msg': 'there was and error while looking for recipe ingredients', 'status_code': 500 } response = RecipeSchema(only=params.fields).dump(recipe) response['ingredients'] = RecipeIngredientResponseSchema( many=True).dump(ingredients) return response, None
def save_recipe(recipe_id): # save form as a dict, add edited form, redirect to recipe page url = Recipe.add_edit_recipe(recipe_id, request.form.to_dict()) return redirect(url_for('recipe', recipe=url[0], title=url[1]))
def db_fill(): print("🚧 filling db with testing data...") # from flask_security import create_user, create_role from app import security roles = [ security.datastore.create_role( name="admin", permissions= "manage-application,manage-users,login-as,see-debug,see-other,edit-other", ), security.datastore.create_role( name="application_manager", permissions="manage-application,see-other,edit-other", ), ] for role in roles: role.save() users = [ security.datastore.create_user(username="******", email="*****@*****.**", password="******"), security.datastore.create_user( username="******", email="*****@*****.**", roles=["application_manager"], password="******", ), security.datastore.create_user(username="******", email="*****@*****.**", roles=["admin"], password="******"), ] for user in users: user.save() from app.models.ingredients import Ingredient ingredients = [ Ingredient(name="prvnà surovina", created_by=users[0].id), Ingredient(name="druhá surovina", created_by=users[0].id), Ingredient(name="třetà surovina", created_by=users[0].id), ] for ingredient in ingredients: ingredient.save() from app.models.recipes import Recipe recipe = Recipe(name="prvnà recept", created_by=users[0].id, portion_count=1, is_shared=False) recipe.add_ingredient(ingredients[0], amount=20) recipe.add_ingredient(ingredients[2], amount=10) recipe.save() recipe_2 = Recipe(name="veřejný recept", created_by=users[0].id, portion_count=1, is_shared=True) recipe_2.add_ingredient(ingredients[0], amount=20) recipe_2.add_ingredient(ingredients[2], amount=10) recipe_2.save() print("✅ database ready for testing.")
def index(): recipes = Recipe.get_random() return render_template('index.html', recipes=recipes[0], slideshow=recipes[1])
def recipe(recipe, title): # get a single recipe by its id recipe = Recipe.get_details(recipe) return render_template('recipe.html', recipe=recipe)
def delete_recipe(recipe_id): # delete recipe by recipe id Recipe.delete_recipe(recipe_id) return redirect(url_for('index'))
def editor(url): # get recipe details if recipe is to be edited otherwise its a new recipe recipe = Recipe.get_details(request.args.get('recipe')) if url == 'edit' else False return render_template('editor.html', url=url, recipe=recipe)