def create_meal(): form_create_meal = CreateMeal() print(Activity.find_activities_by_x_category('cukier')) if form_create_meal.validate_on_submit(): ing = { 'carbs_ingredients': form_create_meal.carbs_ingredients.data, 'meat_ingredients': form_create_meal.meat_ingredients.data, 'ingredients': form_create_meal.ingredients.data, 'warzywa_ingredients': form_create_meal.warzywa_ingredients.data, } print(ing, 'whole data with ingredients') meal_name = form_create_meal.meal_name.data ingredients = Meal.ingredients_for_meal(**ing) try: assert (Meal.query.filter_by(name=meal_name).first().name, f' good, {meal_name} meal not exist in database') print(f'the {meal_name} is in the menu') return render_template('meal.html', form_create_meal=form_create_meal, ingredients=ingredients, meal_name=meal_name, in_menu=True) except AttributeError as e: new_meal = Meal( ingredients=ingredients['string_of_ingridients_ids'], name=meal_name) Meal.save_to_db(new_meal) flash(f'we added {new_meal.name} to the menu') return render_template('meal.html', form_create_meal=form_create_meal, ingredients=ingredients, meal_name=meal_name) return render_template('meal.html', form_create_meal=form_create_meal)
def test_meal_repr(self): u = push_dummy_user() list_ = push_dummy_list(u, 'List') a = Meal(list_id=list_.id, name='Meal', order=0) db.session.add(a) db.session.commit() self.assertEqual(a.__repr__(), '<Meal Meal of List List>')
def meal(request): user = request.user meal_type = request.GET['meal_type'] year = int(request.GET['date'].split('/')[2]) month = int(request.GET['date'].split('/')[1]) day = int(request.GET['date'].split('/')[0]) date = datetime.date(year, month, day) day = user.day_set.filter(date=date).first() meal_set = day.meal_set meal = meal_set.meal_set.filter(meal_type=MealType.objects.filter( name=meal_type).first()).first() if meal is None: meal = Meal(meal_type=MealType.objects.filter(name=meal_type).first(), meal_set=meal_set) meal.save() products = meal.mealproduct_set.all() context = { 'meal_type': request.GET['meal_type'], 'day': day, 'meal': meal, 'meal_set': meal_set, 'date': request.GET['date'], 'products': products } return render(request, 'meal.html', context)
def create_default_meals(): '''function to make users admin''' name = input('Enter name of the meal: ') while True: price = input('Enter price: ') try: price = int(price) break except: print('Price should be integer') continue description = input('Add a short description of the meal: ') while True: username = input('Enter name of caterer in charge of this meal: ') user = User.get(username=username) if isinstance(user, User): break else: print('User not available, please provide a valid username.') continue meal = Meal(name=name, price=price, description=description, default=True) meal.user_id = user.user_id meal.save() print('Meal successfully created as default.')
def test_meal_to_dict(self): u = push_dummy_user() list_ = push_dummy_list(u, 'List') a = Meal(list_id=list_.id, name='Meal', order=0) db.session.add(a) db.session.commit() self.assertEqual(a.to_dict(), {'id': 1, 'name': 'Meal'})
def createMeal(self, id = 1): with self.app.app_context(): meal = Meal.query.get(id) if not meal: meal = Meal(name='meal_{}'.format(id), img_path='#', cost=200) meal.save() return meal.id
def post(current_user, self): if not current_user.type_admin: response = jsonify( {"message": "Not authorized to perform this function!"}) response.status_code = 401 return response m_name = request.json.get('m_name') category = request.json.get('category') price = request.json.get('price') if m_name is None or category is None\ or price is None: response = jsonify({"message": "Missing argument!"}) response.status_code = 400 return response if not isinstance(price, float): response = jsonify( {"message": "Price has to be a float number!"}) response.status_code = 400 return response meals = Meal.query.all() for meal in meals: if meal.m_name == m_name: response = jsonify({"message": "Meal already exists!"}) response.status_code = 202 return response meal = Meal(m_name, category, price) meal.save() response = jsonify({"message": "Meal added"}) response.status_code = 201 return response
def _format_meal(self, meal, order): meal_dict = {'category': meal[2].lower(), 'title': meal[0].lower(), 'provider': PROVIDER_NAME, 'owner': self._user, 'quantity': meal[1]} meal_object = Meal(**meal_dict) meal_object.order_id = order.order_id return meal_object
def setUp(self): super(TestMealsApiTestCase, self).setUp() self.admin_token, self.admin = self.login_admin('*****@*****.**') self.user_token, self.customer_user = self.login_test_user( '*****@*****.**') self.meal = Meal(title='lorem ipsum', price=2000, description='lorem ipsum', catering=self.admin.catering) self.meal.save()
def add_test_meal(self, user=None): """ adds a test meal and returns id """ meal = Meal(title='Beef with rice', price=1500, description='lorem desc ipsum') if user: meal.catering = user.catering meal.save() return meal
def create_meal(): data = request.get_json() or {} meal = Meal() if (meal.from_dict(data) == -1): return bad_request('must include all fields') else: db.session.add(meal) db.session.commit() response = jsonify(meal.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_meal', id=meal.meal_id) return response
def createmeal(request): group = request.POST['group'] if group == '': messages.add_message(request, messages.INFO, "Invalid name. Please try again.") return HttpResponseRedirect('/') elif Meal.objects.filter(group=group).exists(): messages.add_message(request, messages.INFO, "Already exists!") return HttpResponseRedirect('/') else: # success new_meal = Meal(group=group, restaurant="Ryan's Gourmet Hotdogs") new_meal.save() return HttpResponseRedirect('/meal/'+group)
def put_meals(list_id): req = request.get_json() if not req: raise APIError("application/json is required") if not isinstance(req, list): raise APIError("A list of meals is required") list_ = List.query.filter_by(id=list_id).first() meals = Meal.query.filter_by(list_id=list_.id).all() # verify integrity of received list verify_meals(req, meals) for meal in meals: if meal.id not in [i["id"] for i in req if "id" in i]: db.session.delete(meal) db.session.commit() meals = Meal.query.filter_by(list_id=list_.id).all() for index, req_meal in enumerate(req): if "id" in req_meal and req_meal["id"] in [i.id for i in meals]: meals_index = [i.id for i in meals].index(req_meal["id"]) meals[meals_index].order = index meals[meals_index].name = req_meal["name"] else: new_meal = Meal( list_id=list_.id, name=req_meal["name"], order=index ) db.session.add(new_meal) db.session.commit() json_obj = [meal.to_dict() for meal in list_.get_or_create_meals()] return jsonify(json_obj)
def test_get_meals(self): u = push_dummy_user() push_dummy_list(u, 'TestyList') with self.test_client: self.login(u.username) rsp = self.test_client.get('/api/lists/1/meals') data = rsp.get_json() self.assertEqual(rsp.status, '200 OK') self.assertEqual(data, [{ 'id': 1, 'name': 'Lunch' }, { 'id': 2, 'name': 'Dinner' }]) list_ = List.query.first() db.session.add(Meal(list_id=list_.id, name='Test', order=2)) db.session.commit() rsp = self.test_client.get('/api/lists/1/meals') data = rsp.get_json() self.assertEqual(rsp.status, '200 OK') self.assertEqual(data, [{ 'id': 1, 'name': 'Lunch' }, { 'id': 2, 'name': 'Dinner' }, { 'id': 3, 'name': 'Test' }])
class MealsCrud(Resource): method_decorators = [token_required] @swag_from('api-docs/add_meal.yml') def post(self, current_user): data = request.get_json() user_id = current_user["user_id"] if type(data['price']) == unicode: try: map(int, data['price'].split()) return make_response( jsonify({'message': "Please put in an integer"}), 401) except ValueError, IndexError: return make_response( jsonify({'message': "Please put in an integer"}), 401) for meal in meals_db: if data['name'] == meal['details'].name: return make_response( jsonify( {'message': "Meal option already exists, try another"}), 401) meal = Meal(data['name'], data['price'], user_id) meal_prof = { "details": meal, "meal_id": meal.generate_id(len(meals_db)) } meals_db.append(meal_prof) return make_response( jsonify({'message': "Successfully added meal option"}), 201)
def createMenuItem(self, id=1): with self.app.app_context(): menu_item = MenuItem.query.get(id) if not menu_item: menu = Menu.query.get(1) if not menu: menu = Menu(category=MenuType.BREAKFAST) menu.save() meal_name = 'ugali' meal = Meal.query.filter_by(name=meal_name).first() if not meal: meal = Meal(name=meal_name, img_path='#', cost=200) meal.save() menu_item = MenuItem(menu_id=menu.id, meal_id=meal.id) menu_item.save() return menu_item.id
def test_user_can_access_menu(self): """Test user can access the menu (GET request).""" date = datetime.utcnow().date() menu = Menu(date=date) meal = Meal(name='Beef', description='Saucy beef', price=10) meal.save() menu.add_meal_to_menu(meal) menu.save() result = self.login_user() self.assertEqual(200, result.status_code) access_token = json.loads(result.data.decode())['access_token'] res = self.client().get('api/v1/menu/', headers=dict(Authorization="Bearer " + access_token)) self.assertEqual(res.status_code, 200) self.assertEqual('Here is the menu for today', json.loads(res.data.decode('utf-8'))['message'])
def menu_manipulation(): auth_header = request.headers.get('Authorization') if auth_header: access_token = auth_header.split(" ")[1] if access_token: user_id = User.decode_token(access_token) if isinstance(user_id, int): current_user = User.query.filter_by(id=user_id).first() if current_user.caterer: menu = Menu.query.order_by('menu.date').all()[-1] if not menu: abort(404) if request.method == "DELETE": menu.delete() return { "message": "Todays menu has been deleted".format(menu.id) }, 200 elif request.method == 'PUT': menu_meals = request.data.get('meal_list', '') date = request.data.get('date', '') menu.delete() if date == '': date = datetime.datetime.now() if menu_meals: meals = [Meal.get(id=id) for id in menu_meals] menu = Menu(date=date) menu.add_meal_to_menu(meals) return { 'message': 'The menu has successfully been updated', 'menu': menu_meals }, 200 return {'message': 'Please add meals to menu'}, 202 menu.save() else: response = { 'message': 'You are not authorized to perform these functions' } return make_response(jsonify(response)), 401 else: # user is not legit, so the payload is an error message message = user_id response = {'message': message} return make_response(jsonify(response)), 401 else: response = {'message': 'Please input access token'} return make_response(jsonify(response)), 401 else: return {'message': 'Please input access token'}
def put(self, meal_id): for meal in meals: if meal_id == meal.meal_id: meal = json.loads(request.data) m = Meal(meal_id = meal.get('meal_id'), meal_name=meal.get('meal_name'), price=meal.get('price'), category=meal.get('category')) result = jsonify({"message": "meal has been modified"}) result.status_code = 200 return result
def delete(): form_category = DeleteCategory() form_activity = DeleteActivity() form_meal = DeleteMeal() all_cat = Category.json_all() if form_category.validate_on_submit( ) and form_category.submit_delete_category.data: a_category = Category.find_by_id(_id=form_category.category_id.data) Category.delete_from_db(a_category) # print(f'well done, we changed {form_category.name} into {form_category.category_name.data}') print(f'Successful deleted category') return render_template('delete.html', form_activity=form_activity, form_category=form_category, form_meal=form_meal) if form_activity.validate_on_submit( ) and form_activity.submit_delete_activity.data: try: a_activity = Activity.find_by_id(form_activity.activity_id.data) except: flash(f'well done, we added {form_activity.activity_id.data}') Activity.delete_from_db(a_activity) print(f'Successful deleted category') return render_template('delete.html', form_activity=form_activity, form_category=form_category, form_meal=form_meal, added_activity=True) if form_meal.validate_on_submit() and form_meal.submit_delete_meal.data: a_meal = Meal.find_by_id(_id=form_meal.meal_id.data) Meal.delete_from_db(a_meal) # print(f'well done, we changed {form_category.name} into {form_category.category_name.data}') print(f'Successful deleted category') return redirect( url_for('delete', form_activity=form_activity, form_category=form_category, form_meal=form_meal)) return render_template('delete.html', form_activity=form_activity, form_category=form_category, form_meal=form_meal)
def addItem(Club, week, day, mealCategory, name, descrip): #need to figure out a way to validate user later # if(mealCategory < 4 and User.checkIsAdmin()): # club_id = Club.id # newItem = Item(name=name, descrip=descrip) # menu_id = Menu.query.filter_by(club_id=club_id, week=week).first().id # dayMenu_id = DayMenu.query.filter_by(menu_id=menu_id, day=day).id # meal = Meal.query.filter_by(meanNum=mealCateogry, dayMenu_id=dayMenu_id) # meal.items.append(newItem) # db.session.add(newItem) # #db.session.add(meal) # db.session.commit() # print("added item") # else: # print("unable to add item") club_id = Club.id print("Club ID: {}".format(club_id)) newItem = Item(name=name, descrip=descrip) menu_id = Menu.query.filter_by(club_id=club_id).first().id #if menu_id is None : #need to make a new meal for this week print("Menu ID: {}".format(menu_id)) dayMenu_id = DayMenu.query.filter_by(menu_id=menu_id, day=day).first().id dayMenu_day = DayMenu.query.filter_by(menu_id=menu_id, day=day).first().day dayMenu_menu = DayMenu.query.filter_by(menu_id=menu_id, day=day).first().menu_id if dayMenu_id is None: newDay = DayMenu(day=day) week.dayMenus.append(newDay) print(dayMenu_id) meal = Meal.query.filter_by(mealNum=mealCategory, dayMenu_id=dayMenu_id).first() if meal is None: print("no known meal") newMeal = Meal(mealNum=mealCategory) print(DayMenu.query.get(dayMenu_id)) DayMenu.query.filter_by(day= dayMenu_day,menu_id=dayMenu_menu).first().meals.append(newMeal) db.session.add(newMeal) #db.session.commit() meal = newMeal print(meal) db.session.add(newItem) meal.items.append(newItem) #db.session.add(meal) db.session.commit() print("added item")
def add_mock_meals(self): """ adds mock meals """ meal = Meal(title='lorem meal', price=10000, description='lorem ipsum desc') meal.save() meal2 = Meal(title='Beef with rice', price=1500, description='lorem desc ipsum') meal2.save()
def post(self): meal = request.get_json() m = Meal(meal_id=meal.get('meal_id'), meal_name=meal.get('meal_name'), price=meal.get('price'), category=meal.get('category')) meals.append(m) result = jsonify({"message": "meal added"}) result.status_code = 201 return result
def addToMeals(): #add meal to Meal table userId = current_user.id form = MealForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): meal = Meal(name=form.data['name'], cuisine=form.data['cuisine'], recipe=form.data['recipe']) db.session.add(meal) db.session.commit() #connect the meal and the current user on the userMeals table new_meal = Meal.query.filter(Meal.name == form.data['name']).first() new_meal_dict = new_meal.to_dict() user_meal = UserMeal(user_id=userId, meal_id=new_meal_dict['id']) db.session.add(user_meal) db.session.commit() return meal.to_dict() return 'Hello'
def test_get_or_create_entries(self, mock_get_settings): mock_get_settings.return_value = ListSettings( start_day_of_week=-1, days_to_display=7) u = push_dummy_user() list_ = push_dummy_list(u, 'list_') day_1 = list_.get_or_create_days()[0] self.assertTrue(len(day_1.get_or_create_entries()) == 2) meal = Meal(name='test', list_id=list_.id, order=2) db.session.add(meal) db.session.commit() self.assertTrue(len(day_1.get_or_create_entries()) == 3)
def get_meals(): page = request.args.get("page", 1, type=int) per_page = request.args.get("limit", 5, type=int) data = Meal.to_collection_dict(Meal.query, page, per_page, 'api.get_meals') if data == -1: response = jsonify({'error': 'Not found'}) response.status_code = 404 return response return jsonify(data)
def post_meals(list_id): req = request.get_json() if not req: raise APIError("application/json is required") if "name" not in req: raise APIError("name is required") list_ = List.query.filter_by(id=list_id).first() if Meal.query.filter_by(name=req["name"], list_id=list_.id).first(): raise APIError(f'Meal {req["name"]} already exists') try: order = 1 + max( [i.order for i in Meal.query.filter_by(list_id=list_.id).all()] ) except ValueError: order = 1 meal = Meal(list_id=list_.id, name=req["name"], order=order) db.session.add(meal) db.session.commit() json_obj = [meal.to_dict() for meal in list_.get_or_create_meals()] return jsonify(json_obj), 201
def menu(): auth_header = request.headers.get('Authorization') if auth_header: access_token = auth_header.split(" ")[1] if access_token: user_id = User.decode_token(access_token) if isinstance(user_id, int): current_user = User.query.filter_by(id=user_id).first() if request.method == "POST": if current_user.caterer: menu_meals = request.data.get('meal_list', '') date = request.data.get('date', '') if date == '': date = datetime.datetime.now() if menu_meals: meals = [Meal.get(id=id) for id in menu_meals] menu = Menu(date=date) menu.add_meal_to_menu(meals) return { 'message': 'Todays menu has been updated' }, 201 return {'message': 'Please add meals to menu'}, 202 else: response = { 'message': 'You are unauthorized to access this' } return make_response(jsonify(response)), 401 else: # GET menu = Menu.query.order_by('menu.date').all()[-1] menu_meals = [item.make_dict() for item in menu.meals] return { 'message': 'Here is the menu for today', 'menu': menu_meals }, 200 else: # user is not legit, so the payload is an error message message = user_id response = {'message': message} return make_response(jsonify(response)), 401 else: response = {'message': 'Please input access token'} return make_response(jsonify(response)), 401 else: return {'message': 'Please input access token'}
def get(self): args = self.reqparse.parse_args() if args['feature'] == 'total_orders': meals = Meal.query(Meal.id, Meal.label, func.count(PatientMeal.id).label('total_orders')) \ .join(PatientMeal) \ .group_by(Meal.id, Meal.label) \ .all() return { 'meals': marshal([meal for meal in meals], meal_order_fields) } else: abort(400)
def post(self): args = self.reqparse.parse_args() meal = Meal() meal.label = args['label'] meal.total_quantity = args['total_quantity'] meal.current_quantity = args['total_quantity'] meal.time_of_day = args['time_of_day'] db.session.add(meal) db.session.commit() return {'meal': marshal(meal, meal_fields)}, 201
def test_get_or_create_meals(self): u = push_dummy_user() list_no_meals = push_dummy_list(u, 'List') list_with_meals = push_dummy_list(u, 'List (With Meals)') list_no_meals.get_or_create_meals() self.assertEqual([{'id': i.id, 'name': i.name, 'order': i.order} for i in list_no_meals.meals], [{'id': 2, 'name': 'Dinner', 'order': 1}, {'id': 1, 'name': 'Lunch', 'order': 0}]) new_meal = Meal(list_id=list_with_meals.id, name='Mymeal', order=0) db.session.add(new_meal) db.session.commit() list_with_meals.get_or_create_meals() self.assertEqual( [{'id': i.id, 'name': i.name, 'order': i.order} for i in list_with_meals.meals], [{'id': 3, 'name': 'Mymeal', 'order': 0}])