def addRecipes(): form = AddRecipe() if form.validate_on_submit(): parent = Recipes(recipe_name=form.name.data, recipe_type=form.rec_type.data, recipe_info=form.info.data, hearts=form.hearts.data, sell_price=form.sell_price.data ) try: db.session.add(parent) db.session.commit() flash("added recipe") except: db.session.rollback() flash('error could not add recipe') try: for item in form.recipe_needs.data: item_query = Ingredients.query.filter(Ingredients.id==item).first() parent.contains.append(item_query) db.session.add(parent) db.session.commit() flash(('added recipe/ingred', item_query)) except: db.session.rollback() flash("could not add ingredinets") else: flash('not validating') return render_template('addRecipes.html', form=form)
def save_recipe(): if request.method == 'POST': recipe_name = request.form.get('title') recipe_url = request.form.get('url') user_id = request.form.get('user') recipe_type = request.form.get('type') # Find the user user = User.query.filter_by(id=user_id).first() new_recipe = Recipes(recipe_name=recipe_name, source_url=recipe_url, added_by=user.id, type_recipe=recipe_type) # Add the new recipe to the db db.session.add(new_recipe) db.session.commit() return "Successful POST request"
def recipes(): if request.method == "POST": data = request.get_json() recipe_name = data['name'] recipe = Recipes.query.filter_by(name=recipe_name).first() if not recipe: new_recipe = Recipes(name=data['name'], prep_time=data['prep_time'], difficulty=data['difficulty'], vegetarian=data['vegetarian'], rating=data['rating']) new_recipe.rating_numbering = 1 new_recipe.save() response = jsonify({ 'id': new_recipe.id, 'name': new_recipe.name, 'prep_time': new_recipe.prep_time, 'difficulty': new_recipe.difficulty, 'vegetarian': new_recipe.vegetarian, 'rating': new_recipe.rating }) response.status_code = 201 return response else: response = jsonify({'message': 'recipie already exist'}) response.status_code = 304 return response else: # GET recipes = Recipes.get_all() results = [] for recipe in recipes: obj = { 'id': recipe.id, 'name': recipe.name, 'prep_time': recipe.prep_time, 'difficulty': recipe.difficulty, 'vegetarian': recipe.vegetarian } results.append(obj) response = jsonify(results) response.status_code = 200 return response
def get(self, user_in_session, category_id): # This method will retrieve all the recipes under the category given """ Retrieve recipes --- tags: - Recipes Endpoints parameters: - in: path name: category_id description: category id type: integer required: true - in: query name: q description: Search parameter type: string - in: query name: page description: page number type: integer default: 1 - in: query name: limit description: Limit type: integer default: 10 responses: 201: description: Category created successfully 400: description: Invalid page number or limit 401: description: Recipe not found 422: description: Please fill all the fields """ page_number = request.args.get("page", default=1, type=int) no_items_per_page = request.args.get("limit", default=8, type=int) search_recipe = request.args.get('q') # These are the arguments to be provided in the url check_category_exists = Categories.query.filter_by( id=category_id).first() category_recipes = Recipes.get_all(category_id, user_in_session).\ paginate(page_number, no_items_per_page, error_out=True) # This retrieves all the recipes belonging to a specific category. recipe_list = [] if check_category_exists: if search_recipe: # This filters the recipes when the user provides the search parameters q. search_recipes = Recipes.query.filter(Recipes.users_id == user_in_session, Recipes.recipe_name.ilike('%' + search_recipe + '%')). \ paginate(page_number, no_items_per_page, error_out=False) for recipes in search_recipes.items: # This loops retrieves all the recipes that match the search string. searched_recipes = { 'id': recipes.id, 'recipe_name': recipes.recipe_name, 'recipe_description': recipes.recipe_description, 'category_id': recipes.category_id, 'date_created': recipes.created_at, 'date_updated': recipes.updated_at } recipe_list.append(searched_recipes) if len(recipe_list) <= 0: # This checks whether the searched recipe list contains data. return make_response( jsonify({'message': "Recipe does not exist."})), 404 list_of_recipes = { 'recipes': recipe_list, "total_items": search_recipes.total, "total_pages": search_recipes.pages, "current_page": search_recipes.page } return make_response(jsonify(list_of_recipes)), 200 else: for recipes in category_recipes.items: # This loops all the recipes of the category with no search parameters. all_recipes = { 'id': recipes.id, 'recipe_name': recipes.recipe_name, 'recipe_description': recipes.recipe_description, 'category_id': recipes.category_id, 'date_created': recipes.created_at, 'date_updated': recipes.updated_at, 'category_name': check_category_exists.category_name } recipe_list.append(all_recipes) if len(recipe_list) <= 0: return make_response( jsonify({'message': "No recipes for this category."})), 402 list_of_recipes = { 'recipes': recipe_list, "total_items": category_recipes.total, "total_pages": category_recipes.pages, "current_page": category_recipes.page } return make_response(jsonify(list_of_recipes)), 200 return make_response(jsonify({'message': "Category does not exist."})), 406
def post(self, user_in_session, category_id): # This method will create and save a recipe """ Create Recipe --- tags: - Recipes Endpoints parameters: - in: path name: category_id description: category_id type: integer - in: body name: Recipes details description: Create recipe by providing recipe name and description type: string required: true schema: id: create_recipes properties: recipe_name: default: Ugali recipe_procedure: default: Boil water; Put flour; mix the water and flour for five min; serve ugali. responses: 201: description: Recipe created successfully 409: description: Recipe exists! 400: description: Invalid recipe name given 404: description: Category not found 422: description: Please fill all the fields """ recipe_name = str(request.data.get('recipe_name', '')).strip() recipe_procedure = str(request.data.get('recipe_procedure', '')).strip() check_recipe_existence = Recipes.query.filter_by( users_id=user_in_session, category_id=category_id).all() # This checks whether the catgory specified has the a similar category name from the user. if not recipe_name or not recipe_procedure: return make_response( jsonify({'message': 'Please fill all the fields'})), 400 if not re.search(self.regex_recipe_name, recipe_name): return make_response( jsonify({'message': 'Invalid recipe name given'})), 400 for recipe_in_list in check_recipe_existence: recipe_name_in_list = recipe_in_list.recipe_name if recipe_name.upper() == recipe_name_in_list.upper(): return make_response( jsonify({'message': 'Recipe name exists!'})), 409 recipes_save = Recipes(recipe_name=recipe_name, recipe_description=recipe_procedure, category_id=category_id, users_id=user_in_session) recipes_save.save() # This saves the category after it passes all the conditions. return make_response( jsonify({'message': 'Recipe created successfully'})), 201
def create_test_db_entries(): """ Create fake database entries for a test run""" db.create_all() recipe1 = Recipes(recipe_name="Recipe 1", default_weight=10, bagging=True, washing=False) recipe2 = Recipes(recipe_name="Recipe 2", default_weight=5, bagging=True, washing=False) recipe3 = Recipes(recipe_name="Recipe 3", default_weight=15, bagging=False, washing=True) recipe4 = Recipes(recipe_name="Recipe 4", default_weight=20, bagging=False, washing=True) db.session.add(recipe1) db.session.add(recipe2) db.session.add(recipe3) db.session.add(recipe4) db.session.commit() prod_line1 = ProductionLines(line_name="Washing 1", bagging=False, washing=True) prod_line2 = ProductionLines(line_name="Washing 2", bagging=False, washing=True) prod_line3 = ProductionLines(line_name="Bagging 1", bagging=True, washing=False) prod_line4 = ProductionLines(line_name="Bagging 2", bagging=True, washing=False) db.session.add(prod_line1) db.session.add(prod_line2) db.session.add(prod_line3) db.session.add(prod_line4) db.session.commit() antenna1 = Antennas(antenna_port=1, production_line_name="Washing 1", position_name="Washing 1 Start", start=True, end=False) antenna2 = Antennas(antenna_port=2, production_line_name="Washing 1", position_name="Washing 1 End", start=False, end=True) db.session.add(antenna1) db.session.add(antenna2) db.session.commit() tray1 = Trays(rfid="E20041026708007026100E9D") db.session.add(tray1) db.session.commit()
def recipes(id): auth_header = request.headers.get('Authorization') if auth_header: access_token = auth_header.split(" ")[1] else: return {"Message": "Please provide an access token"}, 300 category = RecipeCategory.query.filter_by(id=id).first() result = [] if access_token: user_id = User.decode_token(access_token) if not isinstance(user_id, str): page = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', 20)) if category: if request.method == 'GET': if category.recipes: recipe_object = category.recipes.paginate( page=page, per_page=per_page) for recipe in recipe_object.items: obj = { "id": recipe.id, "name": recipe.name, "Recipe": recipe.recipe, "Date Created": recipe.date_created, "Date Modified": recipe.date_modified } result.append(obj) response = jsonify( { 'Next Page': recipe_object.next_num, 'Prev Page': recipe_object.prev_num, 'Has next': recipe_object.has_next, 'Has previous': recipe_object.has_prev }, result) response.status_code = 200 return response else: response = jsonify( {"Message": "No recipes added yet"}) response.status_code = 404 return response elif request.method == 'POST': name = request.data.get('name', '') recipe = request.data.get('recipe', '') if name and recipe: the_recipes = Recipes(name=name, recipe=recipe, belonging_to=category) the_recipes.save() for recipe in category.recipes.all(): obj = { "id": recipe.id, "name": recipe.name, "Recipe": recipe.recipe, "Date created": recipe.date_created, "Date modified": recipe.date_modified } result.append(obj) response = jsonify(result) response.status_code = 201 return response else: return { "Message": "Please use keys name and recipe" }, 203 else: return {"Message": "Category does not exist"}, 405 else: # Token is not legit so return the error message message = user_id response = jsonify({"Message": message}) response.status_code = 401 return response
def get(self, current_user, id): """"Method to retrieve all the recipes that belong to a category --- tags: - Recipes produces: - application/json security: - TokenHeader: [] parameters: - in: path name: id required: true type: integer - in: query name: page description: The number of pages of the results to be returned - in: query name: limit description: The limit of recipes to be returned by the paginated results responses: 200: schema: id: recipes description: fetching a recipe 400: description: Page Number or limit is not valid 200: description: OK """ page = request.args.get('page', default=1, type=int) limit = request.args.get('limit', default=10, type=int) category_id = id recipes = Recipes.get_all_user_recipes( category_id).paginate(page, limit, error_out=False) results = [] for recipe in recipes.items: recipe_obj = {'id': recipe.id, 'recipe_name': recipe.recipe_name, 'recipe_ingredients': recipe.recipe_ingredients, 'recipe_methods': recipe.recipe_methods, 'category_id': recipe.category_id, 'date_created': recipe.date_created, 'date_modified': recipe.date_modified, 'previous_page': recipes.prev_num, 'next_Page': recipes.next_num } results.append(recipe_obj) if len(results) <= 0: response = {'message': 'No recipe found ', 'status': 'error'} response = make_response(jsonify(response)), 404 return response response = jsonify(results) response.status_code = 200 return response
def post(self, current_user, id): """Method to add a recipe in a category --- tags: - Recipes produces: - application/json security: - TokenHeader: [] parameters: - in: body name: Recipe Register required: true type: string schema: id: recipes properties: recipe_name: type: string default: Panckakes recipe_ingredients: type: long default: Milk, Flour recipe_methods: type: long default: Cook in a pan till ready - in: path name: id required: true type: integer responses: 200: schema: id: recipes 400: description: Bad Request on recipe creation route 201: description: Success in creating a recipe 404: description: Category does not exist """ category_id = id if category_id: try: recipe_name = str(request.data.get('recipe_name', '')) recipe_ingredients = request.data.get('recipe_ingredients', '') recipe_methods = request.data.get('recipe_methods', '') try: recipe_validation(recipe_name, recipe_methods, recipe_ingredients) except Exception as e: response = {'message': str(e)} return make_response(jsonify(response)), 400 recipe = Recipes(recipe_name=recipe_name, recipe_ingredients=recipe_ingredients, recipe_methods=recipe_methods, category_id=category_id, created_by=current_user.id) recipe_details = Recipes.query.filter_by( category_id=category_id, recipe_name=recipe_name, created_by=current_user.id).first() if recipe_details: response = {'message': 'Recipe name exists', 'status': 'fail'} return make_response(jsonify(response)), 400 recipe.save() response = {'id': recipe.id, 'recipe_name': recipe.recipe_name, 'recipe_ingredients': recipe.recipe_ingredients, 'recipe_methods': recipe.recipe_methods, 'category_id': recipe.category_id, 'date_created': recipe.date_created, 'date_modified': recipe.date_modified } response = make_response(jsonify(response)), 201 return response except Exception: response = {'message': 'Category does not exist', 'status': 'error'} return make_response(jsonify(response)), 404