def _add_food(self): name = self.request.get('foodName') calories = calc_foodcalories(name) image = find_image(name) now = datetime.datetime.now().date() f = Food(name = name, calories = calories, calories_left = calories, imagelink = image, time = now) f.put() self.present_food(f)
def render(self, food : model.Food): html = self.template.render(item_name = food.name, energy = food.get_attribute("Energy"), protein = food.get_attribute("Protein"), carbohydrate = food.get_attribute("Carbohydrate"), fat_total = food.get_attribute("Total Fat"), fibre=food.get_attribute("Total Dietary Fibre"), calcium=food.get_attribute("Calcium"), iron=food.get_attribute("Iron"), fat_saturated=food.get_attribute("Fat saturated"), sugar=food.get_attribute("Total Sugar"), salt=food.get_attribute("Sodium") ) return(html)
def manually_add_food(): """Add food to foods, ingredient to ingredients, and food log event to DB""" # add food to foods table new_food = Food.add_or_return_food( food_name=request.form.get('food_name'), brand_name=request.form.get('brand_name')) if not new_food: # add_or_return returns false if food exists flash('Food already exists within DB') return redirect('/manual_add') # add ingredients and link them to the food new_food.add_ingredients_and_links(request.form.get('ingredients')) # add meal to food log time_eaten = request.form.get('time_eaten') new_food_log = FoodLog(meal_id=request.form.get('meal_to_add'), food_id=new_food.id, user_id=session['user_id'], ts=time_eaten) db.session.add(new_food_log) db.session.commit() # redirect to the day for which the food log was added return redirect(f'/{time_eaten[:10]}')
def nutrionix_confirm(nix_id): """Confirms the addition of a nutrionix food search result to the DB""" print(debug) print('NIX_ID:', nix_id) print(debug) result = search_branded_item(nix_id) if not result['nf_ingredient_statement']: # flash('Unfortunately this record has no ingredient info 😢 please try another') return redirect('/add_food') # food_name = result['foods'] new_food = Food.add_or_return_food(food_name=result['food_name'], brand_name=result['brand_name']) if not new_food: # add_or_return returns false if food exists existing_food = Food.query.filter(Food.name == result['food_name'], Food.brand_name == result['brand_name']) \ .first() flash('Food already exists within DB') return redirect(f'/add_food/{existing_food.id}') # add ingredients and link them to the food new_food.add_ingredients_and_links(result['nf_ingredient_statement']) return redirect(f'/add_food/{new_food.id}')
def load_food(food_filename): """Load movies from u.item into database.""" print("Food") for i, row in enumerate(open(food_filename)): row = row.rstrip() # clever -- we can unpack part of the row! # movie_id, title, released_str, junk, imdb_url = row.split("|")[:5] # The date is in the file as daynum-month_abbreviation-year; # we need to convert it to an actual datetime object. # if released_str: # released_at = datetime.datetime.strptime(released_str, "%d-%b-%Y") # else: # released_at = None # Remove the (YEAR) from the end of the title. # title = title[:-7] # " (YEAR)" == 7 food = Food(name=name, carbs=carbs) # We need to add to the session or it won't ever be stored db.session.add(food) # provide some sense of progress if i % 100 == 0: print(i) # Once we're done, we should commit our work db.session.commit()
def add_food(): """Adds ingredient to Food database, adds refrigerator""" ingredient = request.form['ingredient'] quantity_input = request.form['quantity'] quantity = int(quantity_input) added_on = str(datetime.now()) # get user_id from session user_id = session['user'] # add to Food table food = Food(food=ingredient, quantity=quantity, added_on=str(datetime.now())) db.session.add(food) db.session.commit() # get food_id food_id = food.food_id # add to Refrigerator table refrigerator = Refrigerator(user_id=user_id, food_id=food_id) db.session.add(refrigerator) db.session.commit() return jsonify(ingredient)
def post(self): nameOfFood = self.request.get('food-name', allow_multiple=True) dateOfExpiration = self.request.get('expirationDate', allow_multiple=True) pickYourTitle = self.request.get('title') #fill list with key values listOfFoods = [] for i in range(len(nameOfFood)): food = Food(food=nameOfFood[i], expirationDate=datetime.strptime( dateOfExpiration[i], '%Y-%m-%d')) foodKey = food.put() listOfFoods.append(foodKey) #save to grocery list to database groceryToSave = Grocery(title=pickYourTitle, foods=listOfFoods) groceryToSave.put() self.redirect('/loadlist')
def database_info_patch(ndbno, complete_measurement, food_name): """Takes the information from the USDA data pull and puts it into the local database""" # Take the arguments passed and create a new entry in the foods table food_insert = Food(food_id=ndbno, food_name=food_name, food_serving=complete_measurement[0], food_serving_unit=complete_measurement[1]) db.session.add(food_insert) db.session.commit()
def callback(self, ch, method, properties, body): try: print(self.queue_name) print(" [x] Received %r" % body.decode()) data_food = json.loads(body.decode()) list_food = [] for item in data_food: food = Food(0, item["name"], item["type_food"], item["price"], item["status"], item["order_total"], item["rate"], item["unit"]) food.set_image(item["image"]) list_food.append(food) self.food_rp.add_list_food(list_food) except Exception as e: print(e) ch.basic_ack(delivery_tag=method.delivery_tag)
def postlisting(): # Handles a new listing being submitted title = request.form.get('title') title = titlecase(title) texture = request.form.get('texture') datemade = request.form.get('datemade') quantity = request.form.get('quantity') freshfrozen = request.form.get('freshfrozen') description = request.form.get('description') allergens = request.form.getlist('allergens') user_id = session['user_id'] phone_number = request.form.get('phone_number') geoCheckbox = request.form.get('geoCheckbox') if len(phone_number) == 17: phone_number = phone_number[4:7]+phone_number[9:12]+phone_number[13:] else: phone_number = None allergen = Allergen.add_allergen(allergens) allergen_id = allergen.allergen_id if geoCheckbox: lat = request.form.get('lat') lng = request.form.get('lng') location = Location.add_location(lat, lng) location_id = location.location_id else: location_id = None Food.add_food(title, texture, datemade, quantity, freshfrozen, description, allergen_id, user_id, location_id, phone_number) flash('Your mush has been successfully posted!') return redirect('/home')
def load_food(): """Load food from a list of sweets.""" # print statement for testing print('Food') for _ in range(10): food_name = random.choice(sweets) cost = random.randint(1, 38) sweet_food = Food(food_name=food_name, cost=cost, ) db.session.add(sweet_food) db.session.commit()
def find_foods_worked_off(self, e): foods = Food.all() foods.filter("calories_left >", 0) res = [] calories = int(calc_exercisecalories(e.burnrate, e.duration)) for food in foods: res.append(food) if food.calories_left > calories: food.calories_left -= calories food.put() break else: calories -= food.calories food.calories_left = 0 food.put() return res
def intake_form(user_id): """Show intake form and process.""" if request.method == 'POST': if 'user_id' in session: user = User.query.filter_by(user_id=session["user_id"]).first() user_id = user.user_id cost = request.form["cost"] food = request.form["food"] user_food = Food.query.filter(Food.food_name == food, Food.cost == cost).first() if user_food: print(user_food) print(user_food.food_id) if not user_food: # if the query comes out empty user_food = Food(food_name=food, cost=cost) print(user_food) db.session.add(user_food) db.session.commit() date_time = datetime.utcnow() notes = request.form["notes"] sugar = Sugar( user_id=user_id, food_id=user_food.food_id, notes=notes, date_time=date_time, ) print(sugar) db.session.add(sugar) db.session.commit() # flash(f"Food {food} added.") return redirect(f"/user_dashboard/{user_id}") # route to be a string return render_template("user_intake.html", user_id=user_id)
def sql_saver(): restaurants = open("static/json/food.txt") for restaurant in restaurants: restaurant = restaurant.strip() restaurant_data = restaurant.split('|') name = restaurant_data[0].title() description = restaurant_data[1][:200] location = restaurant_data[2] lift_id = int(restaurant_data[4]) yelp_id = restaurant_data[5] # import pdb; pdb.set_trace() lift_obj = Lift.query.filter(Lift.lift_id == lift_id).first() new_restaurant = Food(name=name, description=description, location=location, yelp_id=yelp_id) db.session.add(new_restaurant) # adding relationship new_restaurant.lifts.append(lift_obj) db.session.commit()
def parse(self, response): # os.system('dropdb whistler') # os.system('createdb whistler') # db.create_all() # r = requests.get('https://www.whistlerblackcomb.com/the-mountain/mountain-conditions/terrain-and-lift-status.aspx') skiruns_str = Selector( response=response).xpath('//script/text()').extract()[8] skiruns = json.loads(skiruns_str.split("=")[1].split(";")[0]) lifts = skiruns['Lifts'] #add all lifts to the DB for lift_dict in lifts: liftname = lift_dict['Name'] liftstatus = lift_dict['Status'] mountain = lift_dict['Mountain'] new_lift = Lift(name=liftname, status=liftstatus, mountain=mountain) # import pdb; pdb.set_trace() db.session.add(new_lift) db.session.commit() # a list of dictionaries, with all the data of ski runs, separated by lifts runs_list = skiruns['GroomingAreas'] # lifts_dict is a dictionay where the key 'Runs' has a value of a # list with all ski runs that belong to the lift. The key 'Name' has a value # of each lift that services those runs, split by "-" for lifts_dict in runs_list: #add all the runs to the DB skirun_list = lifts_dict['Runs'] # list of lift names separated by '-' lift_names = lifts_dict['Name'] if lift_names == 'The Peak - T-Bar': lift_names = ['The Peak', 'T-Bars'] else: lift_names = lift_names.split(" - ") # each ski run list is a list of runs that belong to one lift for skirun in skirun_list: skirun_name = skirun['Name'] if '/' in skirun_name: skirun_name = skirun_name.replace('/', '-') skirun_status = skirun['IsOpen'] skirun_groomed = skirun['IsGroomed'] level = skirun['Type'] new_run = Skirun(name=skirun_name, groomed=skirun_groomed, status=skirun_status, level=level) import pdb pdb.set_trace() db.session.add(new_run) db.session.commit() #make the connections for lift_name in lift_names: # Change to the same lift names in the scrape if lift_name == 'Crystal Zone': lift_name = 'Crystal Ridge Express' if lift_name == 'Freestyle Half-pipes': lift_name = 'Catskinner Chair' if lift_name == 'Symphony Amphitheatre': lift_name = 'Symphony Express' if lift_name == 'The Peak': lift_name = 'Peak Express' if lift_name == 'Glacier': lift_name = 'Showcase T-Bar' if lift_name == 'Habitat Terrain Park': lift_name = 'Emerald Express' lift_obj = Lift.query.filter( Lift.name.contains(lift_name)).first() # adding relationship for run in skirun_list: skirun_name = run['Name'] if '/' in skirun_name: skirun_name = skirun_name.replace('/', '-') run_obj = Skirun.query.filter( Skirun.name == skirun_name).first() lift_obj.skiruns.append(run_obj) db.session.commit() categorieslst = ['tree', 'groomer', 'park', 'bowl'] for category in categorieslst: add_category = Category(cat=category) db.session.add(add_category) db.session.commit() levels = ['green', 'blue', 'black'] for level in levels: add_level = SkillLevel(level=level) db.session.add(add_level) db.session.commit() # add category to each run skiruns = Skirun.query.all() categories = { category.cat: category for category in Category.query.all() } for skirun in skiruns: parks = [ 'Habitat Terrain Park', 'Big Easy Terrain Garden, Sz S', 'Nintendo Terrain Park, sz. M,L', 'Highest Level Park, Sz XL' ] bowls = [ 'Jersey Cream Bowl', 'Rhapsody Bowl', 'Ego Bowl - Lower', 'Ego Bowl - Upper' ] trees = [ '7th Heaven', 'Enchanted Forest', 'Rock & Roll', "Franz's - Upper", "Franz's - Lower" ] # skirun.category relationship if skirun.name in parks: skirun.category = categories['park'] elif skirun.name in bowls: skirun.category = categories['bowl'] elif skirun.name in trees: skirun.category = categories['tree'] else: skirun.category = categories['groomer'] db.session.commit() # Add users to our db users = open("../../../static/json/users.json").read() users = json.loads(users) for user in users: fname = user['fname'] lname = user['lname'] email = user['email'] zipcode = user['zipcode'] # check to see user selected categories if user.get('category'): category = user['category'] # level for fake data rand_level = random.choice(levels) level = SkillLevel.query.filter( SkillLevel.level == rand_level).first() clients = User(fname=fname, lname=lname, email=email, zipcode=zipcode, level_id=level.level_id, password='******') db.session.add(clients) #make the connections for cat in category: user_obj = User.query.filter(User.email == email).first() catusr = Category.query.filter(Category.cat == cat).first() catusr.users.append(user_obj) db.session.commit() ratings = open("../../../static/json/rating.txt").read() ratings = ratings.strip() ratings = ratings.split('|') # loop through the list of comments for comment in ratings: comment = comment[:140] user_id = random.randint(1, 100) rating = random.randint(1, 5) skirun_id = random.randint(1, 142) comments = Rating(user_id=user_id, rating=rating, skirun_id=skirun_id, comment=comment) db.session.add(comments) # commit work to the db db.session.commit() restaurants = open("../../../static/json/food.txt") for restaurant in restaurants: restaurant = restaurant.strip() restaurant_data = restaurant.split('|') name = restaurant_data[0].title() description = restaurant_data[1][:200] location = restaurant_data[2] lift_id = int(restaurant_data[4]) yelp_id = restaurant_data[5] # import pdb; pdb.set_trace() lift_obj = Lift.query.filter(Lift.lift_id == lift_id).first() new_restaurant = Food(name=name, description=description, location=location, yelp_id=yelp_id) db.session.add(new_restaurant) # adding relationship new_restaurant.lifts.append(lift_obj) db.session.commit()
def add_to_wishlist_food(): """When user likes something we add to db""" food_id = request.form.get("food_id") food = ap.get_business(API_KEY, food_id) check_food = Food.query.filter_by(yelp_id=food_id).first() main_categories = [ "Mediterranean", "Chinese", "French", "Italian", "American", "Sushi", "Thai", "Indian", "Mexican" ] print("id: ", food_id, "\n", "food: ", food, "\n", check_food) if check_food != None: food_list = FoodList.query.filter_by(food_id=check_food.food_id, user_id=session["user_id"]).all() else: print(food["categories"]) for alias in food["categories"]: if alias["title"] in main_categories: term = alias["title"] break else: term = "Other" print(term) if "price" not in food: price = None else: price = food["price"] print("Price is: ", price) new_food = Food( yelp_id=food_id, name=food["name"], term=term, price=price, address=(food["location"]["display_address"][0] + ', ' + food["location"]["display_address"][1]), image_url=food["image_url"]) db.session.add(new_food) db.session.commit() food_list = FoodList.query.filter_by(food_id=new_food.food_id, user_id=session["user_id"]).all() if food_list == []: now = datetime.now() date_added = now.strftime('%Y/%m/%d %H:%M:%S') new_food_like = FoodList(user_id=session['user_id'], food_id=new_food.food_id, date_added=date_added, interested=1, shared=None) db.session.add(new_food_like) elif food_list: if food_list[0].interested == None: food_list[0].interested = 1 db.session.commit() return "Success"
def addfood(): foodname = request.form.get("inputfood", "applesauce") profileid = request.form.get("profileid", 1) inputdate = request.form.get("inputdate", "2018-10-07") food_object = Food.query.filter(Food.food_name == foodname).first() if not food_object: print("{} does not exist in SQL. Creating Food".format(foodname)) headers = { "x-app-id": secrets.NUTRITIONIX_ID, "x-app-key": secrets.NUTRITIONIX_KEY, "Content-Type": "application/json" } data = {"query": foodname} r = requests.post( 'https://trackapi.nutritionix.com/v2/natural/nutrients', headers=headers, json=data) json_data = json.loads(r.text).get("foods")[0] nutrient_data = {} for item in json_data.get("full_nutrients"): nutrient_data["attr_{}".format(item['attr_id'])] = item['value'] altr_measures = {} if json_data.get("alt_measures"): for item in json_data.get("alt_measures"): altr_measures[item["measure"]] = item["serving_weight"] str_alt_measures = ", ".join([ "{}:{}".format(key, value) for (key, value) in altr_measures.items() ]) else: str_alt_measures = "" test1 = Food( food_name=json_data.get("food_name"), brand_name=None, serving_qty=json_data.get("serving_qty"), serving_unit=json_data.get("serving_unit"), serving_weight_grams=json_data.get("serving_weight_grams"), calories=json_data.get("nf_calories", 0), carbohydrates=json_data.get("nf_total_carbohydrate", 0), fiber=json_data.get("nf_dietary_fiber", 0), fat=json_data.get("nf_total_fat", 0), protein=json_data.get("nf_protein", 0), vitA=nutrient_data.get("attr_320", 0), vitC=nutrient_data.get("attr_401", 0), vitD=nutrient_data.get("attr_328", 0), vitE=nutrient_data.get("attr_323", 0), vitB6=nutrient_data.get("attr_415", 0), vitB12=nutrient_data.get("attr_418", 0), thiamin=nutrient_data.get("attr_404", 0), riboflavin=nutrient_data.get("attr_405", 0), niacin=nutrient_data.get("attr_406", 0), folate=nutrient_data.get("attr_417", 0), calcium=nutrient_data.get("attr_301", 0), copper=nutrient_data.get("attr_312", 0), iodine=0, iron=nutrient_data.get("attr_303", 0), magnesium=nutrient_data.get("attr_304", 0), phosphorus=nutrient_data.get("attr_305", 0), selenium=nutrient_data.get("attr_317", 0), zinc=nutrient_data.get("attr_309", 0), potassium=json_data.get("nf_potassium") / 1000, sodium=nutrient_data.get("attr_307", 0) / 1000, chloride=0, alt_measures=str_alt_measures) db.session.add(test1) db.session.commit() print(test1.food_id) else: print(food_object) print("FOOD IS FOUND. DONT MESS UP") newfood = Food.query.filter(Food.food_name == foodname).first() print(newfood) newrecord = Record(profile_id=profileid, food_id=newfood.food_id, date=inputdate, serving_qty=0, serving_unit=newfood.serving_unit, serving_weight_grams=newfood.serving_weight_grams) db.session.add(newrecord) db.session.commit() print(newrecord.record_id) return render_template("record_ajax.html", item=newrecord)
def load_food(): Food.query.delete() test1 = Food(food_name="AppleSauce", brand_name=None, serving_qty=1, serving_unit="container", serving_weight_grams="111", calories=75.48, carbohydrates=19.41, fiber=1.33, fat=0.19, protein=0.18, vitA=1, vitC=1, vitD=1, vitE=1, vitB6=1, vitB12=1, thiamin=1, riboflavin=1, niacin=1, folate=1, calcium=1, copper=1, iodine=1, iron=1, magnesium=1, phosphorus=1, selenium=1, zinc=1, potassium=1, sodium=1, chloride=1, alt_measures="cup: 246, container: 111, pouch: 90, g: 100") test2 = Food(food_name="Watermelon Juice", brand_name=None, serving_qty=1, serving_unit="container", serving_weight_grams="111", calories=100, carbohydrates=30, fiber=1.33, fat=0.19, protein=0.18, vitA=1, vitC=1, vitD=1, vitE=1, vitB6=1, vitB12=1, thiamin=1, riboflavin=1, niacin=1, folate=1, calcium=1, copper=1, iodine=1, iron=1, magnesium=1, phosphorus=1, selenium=1, zinc=1, potassium=1, sodium=1, chloride=1, alt_measures="cup: 246, container: 111, pouch: 90, g: 100") db.session.add(test1) db.session.add(test2) db.session.commit()