def myfitnesspal_insert(cls, startdate, enddate): mfp_user = os.getenv("MYFITNESSPAL_USER") mfp_pass = os.getenv("MYFITNESSPAL_PASS") client = myfitnesspal.Client(mfp_user, password=mfp_pass) startdate = datetime.datetime.strptime(startdate, "%d-%m-%Y") enddate = datetime.datetime.strptime(enddate, "%d-%m-%Y") date_generated = [ startdate + datetime.timedelta(days=x) for x in range(0, (enddate - startdate).days + 1) ] mfp_results = [] for date in date_generated: day = client.get_date(date) for x in day.meals: for i in x.entries: entry = i.name.replace("\xa0", " ") totals = i.totals totals["entry"] = entry totals["meal"] = x.name totals["date"] = datetime.datetime.strftime( date, "%Y-%m-%d") mfp_results.append(totals) row_count = 0 for i in mfp_results: q = session.execute(db.insert(cls, values=i, prefixes=["IGNORE"])) row_count = row_count + q.rowcount session.flush() session.commit() logger.info(f"Inserting in table: {cls.__tablename__}") logger.info(f"Attempted insert: {len(mfp_results)}") logger.info(f"Inserted rows: {row_count}")
def load_myfitnesspal(username, password): try: user = myfitnesspal.Client(username, password) except Exception as e: raise e else: return user
def login(): if not request.json or not 'username' in request.json or not 'password' in request.json: return jsonify({"error": "Invalid request format"}), 404 else: if session.get('logged_in'): return jsonify(success=True), 200 else: try: # Strip the unicode username = str(request.json['username']) client = myfitnesspal.Client(username, request.json['password']) clients[username] = client session['logged_in'] = True session['username'] = username print('Querying...') if User.query.filter_by(username=username).first(): print("Successful login.") return jsonify(success=True), 200 else: newUser = User(username, request.json['password']) db.session.add(newUser) db.session.commit() print("User created.") return jsonify(success=True), 200 except ValueError: raise InvalidUsage('Invalid Credentials', status_code=401)
def handle(self, *args, **options): # First get users who have MFP credentials + MFPautosync on autosync_on_queryset = MFPCredentials.objects.filter(mfp_autosync=True) # Iterate throguh these entries for i in autosync_on_queryset: print("Running MFP auto_sync for", i.user) try: client = myfitnesspal.Client( username=i.username, password=i.password, unit_aware=True, ) print("Succesfully logged into mfp client for", i.user) except myfitnesspal.exceptions.MyfitnesspalLoginError: print("Credential login error for", i.user) continue # Update their weights, calories in using auto_sync_helper auto_sync_MFP( user=i.user, start_date=i.mfp_autosync_startdate, client=client ) success_msg = ( "Completed MFP AutoSync for " + str(len(autosync_on_queryset)) + " users" ) self.stdout.write(self.style.SUCCESS(success_msg))
def getdata(): username = request.form['text'] client = myfitnesspal.Client(username) with open("nurition_data.csv", "w") as file: file.write("Date\tCals\tCarbs\tFat\tProtein\tSodium\tSugar\t") file.write("\n") for month in range(1, 4): print("Current Month: {}".format(month)) for day in range(1, monthrange(2020, month)[1]): macros = client.get_date(2020, month, day) if len(macros.totals) != 0: macros = macros.totals date = "2020/" + str(month) + "/" + str(day) file.write(date) file.write("\t") print(date) for i, j in macros.items(): file.write(str(j)) file.write("\t") file.write("\n") date = "" file.close() return render_template('index.html', status="success", file="nutrition_data.csv")
def refresh_calories(engine, db_df): print("REFRESHING CALORIES...") [date_start, date_end] = get_target_date_endpoints('calories', db_df) date_query = date_start date_diff = date_end - date_query days = date_diff.days + 1 client = myfitnesspal.Client('jamieinfinity') diary_dump = [] for i in range(days): diary_data = client.get_date(date_query) diary_dump.append(diary_data) date_query = date_query + datetime.timedelta(days=1) date_values = [[ pd.to_datetime(x.date.strftime('%Y-%m-%d')), get_mfp_calories(x) ] for x in diary_dump] updated_df = insert_values(date_values, 'calories', db_df) # these values are missing or corrupted on the web site / service updated_df.loc[updated_df.index == '2018-09-29', 'calories'] = 2668 updated_df.loc[updated_df.index == '2019-10-30', 'calories'] = 2220 updated_df.loc[updated_df.index == '2019-10-31', 'calories'] = 2008 with engine.connect() as conn, conn.begin(): updated_df.to_sql('fitness', conn, if_exists='replace') return updated_df
def main(): #username = input( "Enter MyFitnessPal username: "******"Enter MyFitnessPal password: "******"textJeff" in sys.argv): textJeff = True if ("textKatie" in sys.argv): textKatie = True mfpClient = myfitnesspal.Client(username, password) yesterday = datetime.datetime.now() - timedelta(days=numberOfDaysAgo) mfpMetrics = MyFitnessPalMetrics(mfpClient, yesterday, username) gradeMessage = mfpMetrics.getGradeMessage() print(gradeMessage) if (textJeff or textKatie): print("Texting message....") twilioClient = TwilioSms() if (textJeff): twilioClient.sendMessage("-\n" + gradeMessage, "+14073739626") if (textKatie): twilioClient.sendMessage("-\n" + gradeMessage, "+14435387234")
def init_client(date): """ boot up mfp with steviehuh """ client = myfitnesspal.Client('steviehuh', 'znPiqk6KMpRJ') client_day = client.get_date(date['year'], date['month'], date['day']) return (client, client_day)
def refresh_calories(engine, db_df): print("REFRESHING CALORIES...") [date_start, date_end] = get_target_date_endpoints('Calories', db_df) date_query = date_start date_diff = date_end - date_query days = date_diff.days + 1 client = myfitnesspal.Client('jamieinfinity') diary_dump = [] for i in range(days): diary_data = client.get_date(date_query) diary_dump.append(diary_data) date_query = date_query + datetime.timedelta(days=1) date_values = [[ pd.to_datetime(x.date.strftime('%Y-%m-%d')), get_mfp_calories(x) ] for x in diary_dump] updated_df = insert_values(date_values, 'Calories', db_df) with engine.connect() as conn, conn.begin(): updated_df.to_sql('fitness', conn, if_exists='replace') return updated_df
def form_valid(self, form): form.instance.user = self.request.user try: client = myfitnesspal.Client( username=form.cleaned_data["username"], password=form.cleaned_data["password"], unit_aware=True, ) except myfitnesspal.exceptions.MyfitnesspalLoginError: messages.info( self.request, "Error connecting to MyFitnessPal with the provided information. Please check your MyFitnessPal account settings and try again.", ) return super().form_invalid(form) messages.success(self.request, "MyFitnessPal Settings Updated") # if auto-sync is checked, we should do a full import of the user's logs mfp_autosync = form.cleaned_data["mfp_autosync"] if mfp_autosync: # run full sync here auto_sync_helper( user=self.request.user, start_date=form.cleaned_data["mfp_autosync_startdate"], client=client, ) messages.info( self.request, "MFP Auto-sync: Importing! For large imports, this may take some time. Thank you for your patience!", ) success_url = reverse_lazy("logs") return super().form_valid(form)
def __init__(self, username=None, password=None): if username is None or password is None: raise ValueError( "Username and password arguments must be provided.") self._username = username self._password = password self._client = myfitnesspal.Client(self._username, self._password)
def main(): """Retrieves and analyzes weight and body fat from MyFitnessPal.""" # retrieve and parse command line arguments args = parse_args() # create MyFitnessPal client client = myfitnesspal.Client(args.username, args.password) # establish a date range, weeks go from Monday to Sunday start_date = datetime.date.today() while start_date.weekday() != 6: start_date += datetime.timedelta(days=1) end_date = (start_date - datetime.timedelta(weeks=args.weeks) + datetime.timedelta(days=1)) # retrieve weight and body fat measurements weight = client.get_measurements('Weight', start_date, end_date) body_fat = client.get_measurements('Body Fat', start_date, end_date) # create list of day objects for every date in the range days = create_days(start_date, end_date, weight, body_fat) # create week objects from the day objects weeks = create_weeks(days) # calculate measurement changes week over week calculate_changes(weeks) # print weekly trend for week in weeks: print week print
def log_myfitpal(user, reqdate): """ Takes a datetime date and user and updates the database with api entry """ client = myfitnesspal.Client(user) api_day = client.get_date(reqdate) if Nutrient.objects.get(date=reqdate).DoesNotExist == True or \ Nutrient.objects.get(date=reqdate) != api_day.totals['calories']: db_meal = Nutrient(date=date, calories=api_day.totals['calories']) db_meal.save()
def post(self): args = parser.parse_args() email = args['email'].strip() password = args['password'].strip() date = datetime.datetime.strptime(args['date'], '%Y-%m-%d') client = myfitnesspal.Client(username=email, password=password) print('logged as {}'.format(email)) result = food_extractor(client, date) return jsonify(result)
def login(): global client error = None if request.method == 'POST': try: client = myfitnesspal.Client(request.form['username'],request.form['password']) except ValueError: error = 'Invalid Credentials. Please try again.' else: return redirect(url_for('home')) return render_template('login.html', error=error)
def get_credentials(): while True: username = input("Enter username: "******"Enter password: "******"Successfully connected!") break except MyfitnesspalLoginError: print("Oops! You entered incorrect credentials. Try again...") return client
def lambda_handler(event, context): yesterday = date.today() - timedelta(1) client = myfitnesspal.Client(os.environ['user'], os.environ['password']) data = client.get_date(yesterday.year, yesterday.month, yesterday.day) client = boto3.client('lambda') client.invoke(FunctionName='savetosheets', InvocationType='Event', Payload=json.dumps(data.totals)) return {'statusCode': 200, 'body': json.dumps(data.totals)}
def get_weight(user, start_day): print("Setting up client for %s. \n" % username) client = myfitnesspal.Client(user) print("Getting data from %s to %s \n" % (start_day, date.today())) weight = client.get_measurements('Weight', start_day) # weight is an ordered dict. ew. date_list = list(weight.keys()) weight_list = list(weight.values()) # Create DataFrame from lists df = pd.DataFrame(list(zip(date_list, weight_list)), columns=['date', 'weight']) df['username'] = user return df
def main(): try: username = sys.argv[1] except IndexError: print("Supply username as first argument") sys.exit() print("Connecting to MyFitnessPal...") mfp_client = myfitnesspal.Client(username) gs_client = pygsheets.authorize() print("Opening spreadsheet...") # TODO: detect if sheet exists sheet = gs_client.open("MFP/" + username)[0] update_sheet_from_mfp(username, mfp_client, sheet)
def update_data_sync(self) -> Dict[str, str]: """Get the actual data from the API""" import myfitnesspal as ext_myfitnesspal today = datetime.date.today() client = ext_myfitnesspal.Client(self._username, self._password) info = client.get_date(today.year, today.month, today.day) weights = client.get_measurements("Weight") goal_calories = info.goals.get("calories", 0) goal_carbohydrates = info.goals.get("carbohydrates", 0) goal_fat = info.goals.get("fat", 0) goal_sodium = info.goals.get("sodium", 0) goal_sugar = info.goals.get("sugar", 0) goal_protein = info.goals.get("protein", 0) total_calories = info.totals.get("calories", 0) total_carbohydrates = info.totals.get("carbohydrates", 0) total_fat = info.totals.get("fat", 0) total_sodium = info.totals.get("sodium", 0) total_sugar = info.totals.get("sugar", 0) total_protein = info.totals.get("protein", 0) water = info.water _, weight = list(weights.items())[0] if len(weights) > 0 else 0 cardio_calories_burned = 0 for exercise in info.exercises[0]: cardio_calories_burned += exercise["calories burned"] result = {} result["goal_calories"] = goal_calories result["goal_carbohydrates"] = goal_carbohydrates result["goal_fat"] = goal_fat result["goal_sodium"] = goal_sodium result["goal_sugar"] = goal_sugar result["goal_protein"] = goal_protein result["total_calories"] = total_calories result["total_carbohydrates"] = total_carbohydrates result["total_fat"] = total_fat result["total_sodium"] = total_sodium result["total_sugar"] = total_sugar result["total_protein"] = total_protein result["cardio_calories_burned"] = cardio_calories_burned result["water"] = water result["weight"] = weight return result
def loginAndCalculate(): # print(request.form['username']) try: client = myfitnesspal.Client(request.form['username'], request.form['password']) except ValueError: return showMain() session['logged_in'] = True numDays = 7 make_chart(client, numDays) session['chart_made'] = True return showChart()
def _sync_make_api_call(self) -> bool: """syncronous call to the api""" import myfitnesspal as ext_myfitnesspal try: today = date.today() client = ext_myfitnesspal.Client(self._flow_user_name, self._flow_password) info = client.get_date(today.year, today.month, today.day) if info is not None: return True except: # The API will throw an exception if faulty location pass return False
def _make_client(self, mode): """Make a client of type 'mode'""" if mode == 'mfp': try: client = mfp.Client(self._credentials['MFP_USER']) return client except: print "Invalid credentials supplied for myfitnesspal." return None if mode == 'strava': try: client = strava.Client( access_token=self._credentials['STRAVA_TOKEN']) return client except: print "Invalid credentials supplied for strava." return None
def get(self, response, *args, **kwargs): jwt = response.META.get('HTTP_AUTHORIZATION') # url = 'http://localhost:3011/userDetails' url = 'http://fitdash-api/userDetails' headers = {'Authorization': jwt} r = requests.get(url, headers=headers) username = r.json()['username'] userData = MfpMeals.objects.filter(username=username) client = myfitnesspal.Client('premiumliam') endDate = datetime.now().date() startDate = endDate - timedelta(days=2) days = [] while startDate <= endDate: day = client.get_date(startDate) entries = [] for meal in day.meals: foods = [] for food in meal: foods.append({'name': food.name, 'totals': food.totals}) entries.append({'name': meal.name, 'entry': foods}) days.append({ 'date': str(day.date), 'meals': entries, 'totals': day.totals, 'goals': day.goals }) startDate += timedelta(days=1) data = {"username": username, "days": days} # print(data) serializer = MfpMealsSerializer(data=data) if serializer.is_valid(): # serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def do_GET(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() client = myfitnesspal.Client(os.environ.get('USERNAME'), password=os.environ.get('PASSWORD')) date_obj = date.today() delta = timedelta(days=1) data = {} day = client.get_date(date_obj.year, date_obj.month, date_obj.day) if (day.totals == {}): self.wfile.write(json.dumps(data, indent=4).encode()) return meals = day.meals data['meals'] = {} for meal in meals: meal_obj = {'entries': []} meal_obj['total'] = meal.totals data['meals'][meal.name] = meal_obj entries = meal.entries for entry in entries: data['meals'][meal.name]['entries'].append({ 'name': entry.name, 'total': entry.totals }) data['total'] = day.totals data['water'] = day.water data['weight'] = list( client.get_measurements('Weight', date_obj - delta, date_obj).values())[0] self.wfile.write(json.dumps(data, indent=4).encode()) return
def _get_stats(self, ignore_cache_day_count, days): cache = shelve.open(self.local_cache_fname) stats = OrderedDict() mfp = None for day in self._get_mfp_prev_dates(days): day_key = 'mfp{}'.format(str(day)) if (datetime.date.today() - day).days > self.ignore_cache_day_count \ and cache.get(day_key) is not None: stats[day] = cache[day_key] else: if mfp is None: mfp = myfitnesspal.Client(self.usr, self.pwd) stats[day] = self._get_mfp_day(mfp, day) cache[day_key] = stats[day] cache.close() return stats
def main(): login_info = get_login() # 4 weeks ago #start_date = datetime.now() - timedelta(days=28) #start_date = start_date.date() start_date = date(2018, 1, 1) # test date print "Logging in as " + login_info['username'] + "..." client = myfitnesspal.Client(login_info['username'], login_info['password']) print "Opening google sheets worksheet..." worksheet = get_worksheet(login_info) print "Done!" body_weights = client.get_measurements('Weight', start_date) data = get_data(client, start_date) macros = calculate_macros(data) export_data(macros, worksheet)
def __init__( self, hass: HomeAssistant, username: str, password: str, display_name: str ): """Initialize.""" self._username = username self._password = password self.display_name = display_name if len(self.display_name) == 0: self.display_name = self._username self._client = ext_myfitnesspal.Client(self._username, self._password) self.platforms = [] super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, )
def initialize_mfp_client( user: "******") -> "<class 'myfitnesspal.client.Client'>": """ Summary: Create client for communication with myfitnesspal """ for n in range(0, 9): try: logger.info(f'Initializing MFP Client for {user}...') mfpClient = myfitnesspal.Client( os.getenv(f"{user}_USERNAME"), password=os.getenv(f"{user}_PASSWORD")) return mfpClient except Exception as e: if (n == 8): logger.error('exponential timeout did not resolve the issue') # Send SNS message raise ValueError( f'{user} was unsuccessful in initializing their mfpClient yielding the following error={str(e)}' ) else: sleep((2**n) + random.random()) # exponential backoff logger.info(f'exponential backoff retry {n}')
def form_valid(self, form): if self.request.method == "POST": # todo: potentially this needs a lot of api response handling back to the user # todo: create a loading animation/page on form submission so that user does not spam click submit try: client = myfitnesspal.Client( username=self.request.user.mfpcredentials.username, password=self.request.user.mfpcredentials.password, unit_aware=True, ) except myfitnesspal.exceptions.MyfitnesspalLoginError: messages.info( self.request, "Error connecting to MyFitnessPal with the provided information. Please check your MyFitnessPal account settings and try again.", ) return redirect(reverse_lazy("import-credentials-mfp")) merge_helper(user=self.request.user, form=form, client=client) messages.info( self.request, "Importing! For large imports, this may take some time. Thank you for your patience!", ) return super().form_valid(form)