def get(self, rfid): user = UserModel.find_by_rfid(rfid) if user: current_order = int(user.current_order) recipe = RecipeModel.find_by_id(current_order) ingredients = RecipeModel.find_ingredients(current_order) durations = [0, 0, 0, 0] for ingredient in ingredients: durations[ingredient[0]['pump'] - 1] = ingredient[0]['portion'] timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') order = OrderModel(user.id, user.current_order, timestamp) order.save_to_db() return {"durations": durations} awaiting = UserCardRegistrationModel.awaiting_for_card if awaiting: if UserModel.find_by_username(awaiting): UserModel.update_card(awaiting, rfid) return {"durations": [0, 0, 0, 0]} else: return {"message": "No such user"} else: return {"durations": [0, 0, 0, 0]}
def get(self, value): recipe = RecipeModel.find_by_value(value) if recipe: ingredients = RecipeModel.find_ingredients(recipe.id) return {"recipe": recipe.json(), "ingredients": ingredients} return {'message': 'Recipe not found'}, 404
def post(self): recipe = RecipeModel(**request.get_json()) if RecipeModel.findby_name(recipe.name): return { 'message': "Recipe with this name '{}' already exists".format(recipe.name) }, 400 recipe.saveto_db() return {'recipe': recipe_schema.dump(recipe)}, 201
def delete(self, recipe_id): user_id = get_jwt_identity() recipe = FavouriteRecipesModel.find_by_recipe_id_user_id(recipe_id, user_id) if not recipe: return {"message": "Sorry, I couldn't find this recipe among your favourites."}, 404 recipe.delete_from_db() if not FavouriteRecipesModel.find_by_recipe_id(recipe_id): RecipeModel.delete_from_db(recipe_id) return {"message": f"Recipe with the id {recipe_id} removed successfully from your favourites!"}, 200
def setUp(self) -> None: super(TestUsersFavouriteRecipes, self).setUp() with self.app_context(): self.user = UserModel("TestUsername", "TestPwd1!") self.user.save_to_db() recipe = RecipeModel("Title1", "Url1", "Ingredients1, test1") recipe.save_to_db() self.current_time = datetime.utcnow() self.f_recipe = FavouriteRecipesModel(self.user.user_id, recipe.recipe_id, self.current_time, "Meat", "The most delicious ever!")
def test_delete_with_all_recipes(self): with self.app_context(): with self.app() as client: self.assertEqual( RecipeModel.count_all()[0], 3, "The number of recipes saved to db is not correct.") self.assertEqual( len(FavouriteRecipesModel.show_mine(1)), 3, "The number of favourite recipes saved to db is not correct." ) response = client.post( f"{URL}/login", data=json.dumps({ "username": "******", "password": "******" }), headers={"Content-Type": "application/json"}) access_token = json.loads(response.data)['access_token'] response = client.delete(f"{URL}/delete_account/TestUsername", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" }) expected = { "message": f"User's account (username: TestUsername) deleted successfully!", "access_token": None, "refresh_token": None } self.assertEqual( response.status_code, 200, "Status code after deleting a user is not correct.") self.assertEqual( json.loads(response.data), expected, "Message returned after deleting a user is not correct.") self.assertEqual( RecipeModel.count_all()[0], 0, "The number of recipes saved to db after deleting a user is not correct." ) self.assertEqual( len(FavouriteRecipesModel.show_mine(1)), 0, "The number of favourite recipes saved to db after deleting a user is not correct." )
def test_show_all(self): with self.app_context(): self.f_recipe.save_to_db() recipe2 = RecipeModel("Title2", "Url2", "Ingredients2, test2") recipe2.save_to_db() f_recipe2 = FavouriteRecipesModel(self.user.user_id, recipe2.recipe_id, self.current_time) f_recipe2.save_to_db() all_recipes = FavouriteRecipesModel.show_all() self.assertEqual( len(all_recipes), 2, "FavouriteRecipesModel.show_all() does not query the db appropriately." )
def test_show_mine(self): with self.app_context(): self.f_recipe.save_to_db() recipe2 = RecipeModel("Title2", "Url2", "Ingredients2, test2") recipe2.save_to_db() f_recipe2 = FavouriteRecipesModel(self.user.user_id, recipe2.recipe_id, self.current_time) f_recipe2.save_to_db() my_recipes = [ x.json() for x in FavouriteRecipesModel.show_mine(self.user.user_id) ] expected = [{ "recipe_id": 1, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": "Meat", "comment": "The most delicious ever!", "recipe_title": "Title1", "recipe_link": "Url1", "ingredients": "Ingredients1, test1" }, { "recipe_id": 2, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": None, "comment": None, "recipe_title": "Title2", "recipe_link": "Url2", "ingredients": "Ingredients2, test2" }] self.assertListEqual( my_recipes, expected, "FavouriteRecipesModel.show_mine() query does not return proper values." )
def test_show_my_recipe_ids(self): with self.app_context(): self.f_recipe.save_to_db() recipe2 = RecipeModel("Title2", "Url2", "Ingredients2, test2") recipe2.save_to_db() f_recipe2 = FavouriteRecipesModel(self.user.user_id, recipe2.recipe_id, self.current_time) f_recipe2.save_to_db() my_recipes_ids = FavouriteRecipesModel.show_my_recipe_ids( self.user.user_id) self.assertListEqual( my_recipes_ids, [(1, ), (2, )], "FavouriteRecipesModel.show_my_recipe_ids() returns wrong values." )
def get(self): search_obj = {'key_search': None, 'value_search': None} name, calories, instructions = request.args.get( 'name'), request.args.get('calories'), request.args.get( 'instructions') if name: search_obj['key_search'] = 'name' search_obj['value_search'] = name elif calories: search_obj['key_search'] = 'calories' search_obj['value_search'] = calories elif instructions: search_obj['key_search'] = 'instructions' search_obj['value_search'] = instructions recipes = RecipeModel.search_by(search_obj) if recipes: return { 'items': len(recipes), 'recipes': recipe_list_schema.dump(recipes) } return { 'message': 'Search did not found a recipe', 'description': search_obj }, 404
def find_possible_drinks(ingredient_id): possible_drinks_dict = [] possible_drinks = MixingModel.find_by_ingredient(ingredient_id) for row in iter(possible_drinks): drink = RecipeModel.find_by_id(row.recipe_id) possible_drinks_dict.append(drink.json()) return possible_drinks_dict
def post(self): # fetch data from the body as json data = request.get_json() data["ingredients"] = json.dumps(data["ingredients"]) data["sections"] = json.dumps(data["sections"]) # search if that name of the recipe exists if RecipeModel.find_by_title(data["title"]): return { "message": "Recipe already exists", "code": 400, "success": False }, 400 # validate through schemas try: recipe = recipe_schemas.load(data) except ValidationError as err: return err.messages, 500 try: recipe.save_to_db() except: return {"message": "There was an error please try again"}, 500 return { "created": True, "success": True, "code": 201, "recipe": recipe_schemas.dump(recipe) }, 201
def delete(self, id): recipe = RecipeModel.find_by_id(id=id) if recipe is None: return { "message": "recipe was not found", "code": 404, "success": False, }, 404 # delete from db try: recipe.delete_from_db() except: return { "message": "Error with the delete process", "code": 500, "success": False, }, 500 return { "message": "Recipe was deleted", "success": True, "code": 200, "result": recipe_schemas.dump(recipe) }
def get(self, name): recipe = RecipeModel.find_by_name(name) if recipe: return recipe.json(name) return { 'message': "There does not seem to be a recipe for that yet." }, 404
def test_delete_success(self): with self.app_context(): with self.app() as client: recipe_id, _ = RecipeModel("Title1", "Url1", "Ingredients1, test1").save_to_db() FavouriteRecipesModel(1, recipe_id, self.current_time, "Meat", "The most delicious ever!").save_to_db() self.assertIsNotNone( RecipeModel.find_by_recipe_id(1), "While running TestFavouriteRecipeResource.test_delete_success()," "the recipe was not saved successfully to db.") self.assertIsNotNone( FavouriteRecipesModel.find_by_recipe_id(1), "While running TestFavouriteRecipeResource.test_delete_success()," "the favourite recipe was not saved successfully to db.") response = client.delete( f"{URL}/favourite_recipe/1", headers={"Authorization": f"Bearer {self.access_token}"}) expected = { "message": f"Recipe with the id 1 removed successfully from your favourites!" } self.assertDictEqual( json.loads(response.data), expected, "Incorrect message returned while trying to successfully delete " "a favourite recipe.") self.assertEqual( response.status_code, 200, "Incorrect status code returned while trying to successfully delete " "a favourite recipe.") self.assertIsNone( RecipeModel.find_by_recipe_id(1), "While running TestFavouriteRecipeResource.test_delete_success()," "the recipe was not deleted successfully from db.") self.assertListEqual( FavouriteRecipesModel.find_by_recipe_id(1), [], "While running TestFavouriteRecipeResource.test_delete_success()," "the favourite recipe was not deleted successfully from db." )
def delete(self, user_id): claims = get_jwt_claims() if not claims["admin"]: return {"message": "Admin permission required!"}, 403 user_to_delete = UserModel.find_by_id(user_id) user_favourite_recipe_ids = FavouriteRecipesModel.show_my_recipe_ids( user_id) user_to_delete.delete_from_db() # this is to remove the deleted user's recipes from the table 'recipes'/ # if no other user have it saved in their favourites: for recipe_id in user_favourite_recipe_ids: if not FavouriteRecipesModel.find_by_recipe_id(recipe_id[0]): RecipeModel.delete_from_db(recipe_id[0]) return { "message": f"User's account (user_id: {user_id}) deleted successfully!" }, 200
def post(self, value): user = UserModel.find_by_id(current_identity.id) user.current_order = RecipeModel.find_by_value(value).id user.save_to_db() return { "user": current_identity.id, "current_order": current_identity.current_order }
def post(self): data_parser = reqparse.RequestParser() data_parser.add_argument("title", required=True, type=str, help="Please add recipe's title") data_parser.add_argument("href", required=True, type=str, help="Please add recipe's url") data_parser.add_argument("ingredients", required=True, type=str, help="Please add recipe's ingredients") data_parser.add_argument("category", required=False, type=str, help="You can categorize this recipe") data_parser.add_argument("comment", required=False, type=str, help="You can add a comment to this recipe") data = data_parser.parse_args() user_id = get_raw_jwt()['identity'] current_time = datetime.utcnow() recipe_obj = RecipeModel.find_by_href(data['href']) if recipe_obj: recipe_id = recipe_obj.recipe_id else: recipe_id, recipe_obj = RecipeModel(data['title'], data['href'], data['ingredients']).save_to_db() if FavouriteRecipesModel.find_by_recipe_id_user_id(recipe_id, user_id): return {"message": "You have already this recipe saved in your favourites. " "If you want to update it, use the update endpoint."}, 400 favourite = FavouriteRecipesModel(user_id, recipe_id, current_time, data['category'], data['comment']) favourite.save_to_db() just_saved_recipe_display = favourite.json() return {'message': "Successfully saved", "saved_recipe": just_saved_recipe_display}, 201
def delete (self, value): recipe = RecipeModel.find_by_value(value) if recipe: mixings_to_delete = MixingModel.find_by_recipe(recipe.id) for row in iter(mixings_to_delete): row.delete_from_db() recipe.delete_from_db() return {'message': 'Recipe deleted'} return {'message': 'No such recipe'}
def get(self, recipe_id): recipe_obj = RecipeModel.find_by_recipe_id(recipe_id) if recipe_obj: user_id = get_jwt_identity() favourite = FavouriteRecipesModel.find_by_recipe_id_user_id(recipe_id, user_id) if favourite: recipe_to_display = favourite.json() return {"Recipe": recipe_to_display}, 200 return {'message': "Sorry, I couldn't find this recipe in your favourites."}, 404
def post(self, value): recipe_data = Recipe.recipe_parser.parse_args() portion_sum = 0 if RecipeModel.find_by_value(value): return {'message': "Recipe '{}' already exist".format(value)}, 400 recipe = RecipeModel(value, recipe_data['name']) for mixing in iter(recipe_data['ingredients_list']): portion_sum = portion_sum + mixing['portion'] if portion_sum > 200: return {"meessage": "portion over limit"} try: recipe_id = recipe.save_to_db() for mixing in iter(recipe_data['ingredients_list']): mixing_model = MixingModel(mixing['ingredient_id'], recipe_id, mixing['portion']) mixing_model.save_to_db() except: return {'message': 'An error occured during saving to DB'}, 500 return recipe.json(), 201
def setUp(self) -> None: super(TestDeleteAccount, self).setUp() with self.app_context(): with self.app() as client: self.current_time = datetime.utcnow() UserModel("TestUsername", "TestPwd1!").save_to_db() self.recipe_id1, _ = RecipeModel( "Title1", "Url1", "Ingredients1, test1").save_to_db() recipe_id2, _ = RecipeModel( "Title2", "Url2", "Ingredients2, test2").save_to_db() recipe_id3, _ = RecipeModel( "Title3", "Url3", "Ingredients3, test3").save_to_db() FavouriteRecipesModel( 1, self.recipe_id1, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db() FavouriteRecipesModel( 1, recipe_id2, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db() FavouriteRecipesModel( 1, recipe_id3, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db()
def test_show_stats(self): with self.app_context(): self.f_recipe.save_to_db() recipe2 = RecipeModel("Title2", "Url2", "Ingredients2, test2") recipe2.save_to_db() f_recipe2 = FavouriteRecipesModel(self.user.user_id, recipe2.recipe_id, self.current_time) f_recipe2.save_to_db() user2 = UserModel("TestUsername2", "TestPwd1!") user2.save_to_db() f_rec_user2 = FavouriteRecipesModel(user2.user_id, recipe2.recipe_id, self.current_time) f_rec_user2.save_to_db() stats = [(rm.recipe_id, stat) for (rm, stat) in FavouriteRecipesModel.show_stats()] expected = [(1, 1), (2, 2)] self.assertListEqual( stats, expected, "FavouriteRecipesModel.show_stats() produces improper stats.")
def delete(self, recipe_id): data = NewRecipe.parser.parse_args() recipe = RecipeModel.find_by_id(recipe_id) if recipe: if recipe.chef_id == data['chef_id']: recipe.delete_from_db() return {'message': 'Recipe deleted'} else: return { 'message': 'You can not delete this recipe as you are not the chef.' }, 401 return {'message': 'Recipe not found'}, 404
def delete(self, username): current_user_id = get_jwt_identity() current_user = UserModel.find_by_id(current_user_id) if not current_user.username == username: return { "message": "You need to be logged in to the account you want to remove!" }, 401 user_favourite_recipe_ids = FavouriteRecipesModel.show_my_recipe_ids( current_user_id) current_user.delete_from_db() # this is to remove the deleted user's recipes from the table 'recipes'/ # if no other user have it saved in their favourites: for recipe_id in user_favourite_recipe_ids: if not FavouriteRecipesModel.find_by_recipe_id(recipe_id[0]): RecipeModel.delete_from_db(recipe_id[0]) return { "message": f"User's account (username: {username}) deleted successfully!", "access_token": None, "refresh_token": None }, 200
def post(self, id): # make sure the id belongs to a recipe recipe = RecipeModel.find_by_id(id) if recipe is None: return { "message": "Recipe was not found", "success": False, "code": 404 }, 404 # fetch file and save it files = request.files['recipe_cover'] files.filename = "recipe_" + str(id) + "_" + files.filename try: filename = images.save(files) except: return { "message": "Make sure you are uploading an image", "success": False, "code": 500 }, 500 # create new image record image = image_schemas.load({ "name": filename, "data": files.mimetype, "recipe_id": id }) # update the recipe with the filename recipe.image_name = files.filename try: image.save_to_db() recipe.update_to_db() except: return { "message": "There was an error while saving, please try again", "success": False, "code": True }, 500 return { "message": "Image uploaded", "success": True, "code": 201, "result": image_schemas.dump(image) }
def test_put_success(self): with self.app_context(): with self.app() as client: recipe_id, _ = RecipeModel("Title1", "Url1", "Ingredients1, test1").save_to_db() FavouriteRecipesModel(1, recipe_id, self.current_time, "Meat", "The most delicious ever!").save_to_db() response = client.put(f"{URL}/favourite_recipe/1", data=json.dumps({ "category": "Awful", "comment": "Don't ever try again!!" }), headers={ "Content-Type": "application/json", "Authorization": f"Bearer {self.access_token}" }) expected = { "Recipe updated!": { "recipe_id": 1, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": "Awful", "comment": "Don't ever try again!!", "recipe_title": "Title1", "recipe_link": "Url1", "ingredients": "Ingredients1, test1" } } self.assertDictEqual( json.loads(response.data), expected, "Message returned while trying to successfully update a favourite recipe" " is incorrect.") self.assertEqual( response.status_code, 201, "Status code returned while trying to successfully update a favourite recipe" " is incorrect.")
def get(self): uuid = request.args.get("uuid") if not uuid: return { 'message': "Missing uuid parameter", 'description': { 'search_key': 'uuid', 'search_value': uuid } }, 404 recipe = RecipeModel.findby_id(uuid) if recipe: return recipe_schema.dump(recipe), 200 return {'message': "Recipe not found", 'description': uuid}, 404
def delete(self): uuid = request.args.get('uuid') if not uuid: return { 'message': "Missing uuid parameter", 'description': { 'search_key': 'uuid', 'search_value': uuid } }, 404 recipe = RecipeModel.findby_id(uuid) if recipe: recipe.deletefrom_db() return {'message': 'Recipe deleted', 'description': uuid} return {'message': 'Recipe not found', 'description': uuid}, 404
def test_post_as_favourite_recipe_already_existing_in_db(self): with self.app_context(): with self.app() as client: RecipeModel("Test title", "Test url", "Test, ingredients").save_to_db() response = client.post(f"{URL}/favourite_recipe", data=json.dumps({ "title": "Test title", "href": "Test url", "ingredients": "Test, ingredients", "category": "Meat", "comment": "The most delicious ever!" }), headers={ "Content-Type": "application/json", "Authorization": f"Bearer {self.access_token}" }) expected = { 'message': "Successfully saved", "saved_recipe": { "recipe_id": 1, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": "Meat", "comment": "The most delicious ever!", "recipe_title": "Test title", "recipe_link": "Test url", "ingredients": "Test, ingredients" } } self.assertDictEqual( json.loads(response.data), expected, "Message returned when successfully saving a favourite recipe " "(which was already existing in the recipes table) is incorrect.") self.assertEqual( response.status_code, 201, "Status code returned when successfully saving a favourite recipe " "(which was already existing in the recipes table) is incorrect.")