def get(self): ''' get saved meal plan schedule by user name ''' user_col = db_connection['users'] # get the logined username username = current_identity.get('username') u = user_col.find_one({'username': username}) # get meal plan shopping_list = u.get('shopping_list', {}) return {'result': shopping_list}, 200
def get(self): ''' get meal plan for user ''' user_col = db_connection['users'] # get the logined username username = current_identity.get('username') u = user_col.find_one({'username': username}) # get meal plan nt = u.get('nutrition_target', {'calories':0, 'carbon':0, 'fiber':0}) return {'result': nt}, 200
def post(self): ''' update the nutrition traget by username ''' post_data = request.get_json() nutrition_target = post_data.get('nutrition_target', None) if not nutrition_target: return {'result': 'Error please enter nutrition target'}, 403 # only allow ['calories', 'carbon', 'fiber'] if len(nutrition_target) != 3: return {'result': 'invalid input'}, 403 # add checker for int try: for x in nutrition_target: # check value is number temp = int(nutrition_target[x]) # also set limit if x == 'calories' and not (temp<=1000 and temp>=0): raise Exception("invalid range") elif x == 'carbon' and not (temp<=200 and temp>=0): raise Exception("invalid range") elif x == 'fiber' and not (temp<=50 and temp>=0): raise Exception("invalid range") # check key is in the list if x not in ['calories', 'carbon', 'fiber']: raise Exception("key %s is not in list"%x) except Exception as e: print(e) return {'result': str(e)}, 403 user_col = db_connection['users'] # get the logined username username = current_identity.get('username') # set the nutrition with new value to user u = user_col.update( {'username': username}, { '$set':{'nutrition_target': nutrition_target}} ) return {'result': nutrition_target}, 200
def post(self): ''' update the shopping list by username ''' post_data = request.get_json() new_plan = post_data.get('shopping_list', None) # mandetory field for shopping list if not new_plan: return {'result': 'Error please enter shopping list'}, 403 user_col = db_connection['users'] # get the logined username username = current_identity.get('username') u = user_col.update({'username': username}, {'$set': { 'shopping_list': new_plan }}) return {'result': 'success'}, 200
def get(self): ''' aggregate the recipe ingradients in meal planer and return to shopping list ''' # example curl localhost:5000/v1/recipes/ try: # for now tempory user is group3 username = current_identity.get('username') user_col = db_connection['users'] # find the exist key for that user u = user_col.find_one({'username': username}) mp = u.get('meal_plan', {}) # then get all recipe id with count recipe_ids = {} DAYS = [ 'friday', 'monday', 'saturday', 'sunday', 'thursday', 'tuesday', 'wednesday' ] for meals in mp: for days in DAYS: # if we have the plan on that day recipe_per_day = meals[days].get('recipe_id', None) if recipe_per_day: # check if we store the id before if recipe_ids.get(recipe_per_day, None): recipe_ids[recipe_per_day] += 1 else: recipe_ids.update({recipe_per_day: 1}) # then get the recipe by id recipes = [] r_collection = db_connection['recipe'] for rid in recipe_ids: recipe = r_collection.find_one({'_id': ObjectId(rid)}) # also loop over the duplicate for _ in range(recipe_ids[rid]): recipes.append(recipe) # loop over each ingredients to get the quantity and name ret_json = {} for x in recipes: for ingredient in x['ingredients']: try: # Note -1 means the ingredient has no quantity restriction quantity = ingredient.get('quantity', '-1 ') # split into quantity and unit # I assume the format will be 'quantity unit' t = quantity.split(' ') quantity, unit = (Fraction( t[0]), t[1]) if len(t) == 2 else (Fraction(t[0]), None) # only add the unit when the recipe provides q_str = '%s %s' % (str(quantity), unit) if unit else '%s' % ( str(quantity)) type_ = ingredient['type'] name = ingredient['name'] # now start to parse into return value has_ = ret_json.get(name, None) # if the ingredient already in the return update it if has_: ret_json[name]['detail'].append({ 'recipe_id': str(x['_id']), 'recipe_title': x['title'], 'quantity': q_str }) # add up the quantity is not -1 ret_json[name]['total_q'] += quantity # else we create a new one else: ret_json.update({ name: { 'type': type_, 'total_q': quantity, 'unit': unit, 'detail': [{ 'recipe_id': str(x['_id']), 'recipe_title': x['title'], 'quantity': q_str }] } }) except: print(ingredient) # now loop over again to parse the total quantity into string for x in ret_json: total_q = ret_json[x].pop('total_q') unit = ret_json[x].pop('unit') q_str = '%s %s' % (str(total_q), unit) if unit else '%s' % (str(total_q)) ret_json[x].update({'quantity': q_str}) # print(ret_json) except Exception as e: return {'result': str(e)}, 400 return {'result': ret_json}, 200
def post(self): ''' update the meal plan by user name ''' post_data = request.get_json() new_plan = post_data.get('new_plan', None) if not new_plan: return {'result': 'Error please enter new plan'}, 403 user_col = db_connection['users'] # get the logined username username = current_identity.get('username') # but remove the old nutrition first if len(new_plan) > 3: new_plan.pop() # also cleanup the existing shopping list u = user_col.update({'username': username}, { '$set': { 'meal_plan': new_plan, 'shopping_list': {}, 'last_meal_plan_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') } }) # else loop over each recipe to find nutrition r_col = db_connection['recipe'] days = [ "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" ] nutritions = { x: { "Calories": 0, "Carbon": 0, "Fiber": 0, } for x in days } # same here # loop over the existing meal plan to calculate the nutritions for meal in new_plan: for day in days: rid = meal[day].get('recipe_id', None) if rid != None: r = r_col.find_one(ObjectId(rid)) r_nutrition = r['nutritional info']['nutrition facts'] # print(r_nutrition) # add for the number nutritions[day]['Calories'] += float( r_nutrition['CALORIES']['value']) nutritions[day]['Carbon'] += float( r_nutrition['CARB']['value']) nutritions[day]['Fiber'] += float( r_nutrition['FIBER']['value']) # add the header for the rendering nutritions.update({"meals": "Nutrition Target"}) # also return the new plan with nutrition target new_plan.append(nutritions) return {'result': new_plan}, 200
def get(self): ''' get saved meal plan schedule by user name ''' user_col = db_connection['users'] # get the logined username username = current_identity.get('username') u = user_col.find_one({'username': username}) # get meal plan mp = u.get('meal_plan', {}) #we also refresh per week last_time = u.get('last_meal_plan_time') last_datetime = datetime.datetime.strptime(last_time, '%Y-%m-%d %H:%M:%S') # compare with the this week start_weekday = datetime.datetime.today() - datetime.timedelta( days=datetime.datetime.today().isoweekday() % 7) start_weekday = start_weekday.replace(hour=0, minute=0, second=0, microsecond=0) empty_plan = [ { "key": 1, "meals": "Breakfast", "monday": {}, "tuesday": {}, "wednesday": {}, "thursday": {}, "friday": {}, "saturday": {}, "sunday": {} }, { "key": 2, "meals": "Lunch", "monday": {}, "tuesday": {}, "wednesday": {}, "thursday": {}, "friday": {}, "saturday": {}, "sunday": {} }, { "key": 3, "meals": "Dinner", "monday": {}, "tuesday": {}, "wednesday": {}, "thursday": {}, "friday": {}, "saturday": {}, "sunday": {} }, ] # give the empty plan if we got next week if start_weekday > last_datetime: # also set back to database u = user_col.update({'username': username}, {'$set': { 'meal_plan': empty_plan }}) # return {'result': empty_plan}, 200 mp = empty_plan # else loop over each recipe to find nutrition r_col = db_connection['recipe'] days = [ "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" ] nutritions = { x: { "Calories": 0, "Carbon": 0, "Fiber": 0, } for x in days } # then loop over the existing meal plan to calculate the nutritions for meal in mp: for day in days: rid = meal[day].get('recipe_id', None) if rid != None: # find each recipe detail r = r_col.find_one(ObjectId(rid)) r_nutrition = r['nutritional info']['nutrition facts'] # add for the number nutritions[day]['Calories'] += float( r_nutrition['CALORIES']['value']) nutritions[day]['Carbon'] += float( r_nutrition['CARB']['value']) nutritions[day]['Fiber'] += float( r_nutrition['FIBER']['value']) # add the header for the rendering nutritions.update({"meals": "Nutrition Target"}) # also return the new plan with nutrition target mp.append(nutritions) return {'result': mp}, 200
def get_current_identity_user(cls): user_id = '%d' % current_identity.get('id') user = cls.find_by_id(user_id) return user.json()
def get_current_identity_user_id(cls): return '%d' % current_identity.get('id')
def check(cls, *args, **kwargs): if current_identity is not None and current_identity.get( 'type', 'default') in args: return True else: return False