Skip to content

Commit

Permalink
add weekly foods view, update fatsecret tools and url
Browse files Browse the repository at this point in the history
  • Loading branch information
Evgeniy-Golodnykh committed Jan 23, 2025
1 parent c76d04d commit e194533
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 36 deletions.
87 changes: 53 additions & 34 deletions blackfox/fatsecret/tools.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime as dt
import os
from collections import Counter

from rauth import OAuth1Service

Expand All @@ -16,6 +17,7 @@
PARAMS_FOOD_DAILY = {'method': 'food_entries.get.v2', 'format': 'json'}
PARAMS_FOOD_MONTHLY = {'method': 'food_entries.get_month.v2', 'format': 'json'}
PARAMS_WEIGHT = {'method': 'weights.get_month.v2', 'format': 'json'}
FOOD_FIELDS = ['calories', 'carbohydrate', 'fat', 'fiber', 'protein', 'sugar']


fatsecret = OAuth1Service(
Expand All @@ -39,7 +41,7 @@ def unix_date_converter(date):
return (date - epoch).days


def food_caclulator(foods, weight, project, date):
def daily_food_caclulator(foods, weight, project, date):
"""A function for calculating and compiling a daily food diary."""

instance = {
Expand All @@ -55,38 +57,28 @@ def food_caclulator(foods, weight, project, date):
'weight_target': project.target_weight,
}
for food in foods:
instance['calories_actual'] = (
instance.get('calories_actual', 0)
+ int(food.get('calories', 0))
)
instance['carbohydrate_actual'] = round(
(instance.get('carbohydrate_actual', 0)
+ float(food.get('carbohydrate', 0))),
2
)
instance['fat_actual'] = round(
(instance.get('fat_actual', 0)
+ float(food.get('fat', 0))),
2
)
instance['fiber_actual'] = round(
(instance.get('fiber_actual', 0)
+ float(food.get('fiber', 0))),
2
)
instance['protein_actual'] = round(
(instance.get('protein_actual', 0)
+ float(food.get('protein', 0))),
2
)
instance['sugar_actual'] = round(
(instance.get('sugar_actual', 0)
+ float(food.get('sugar', 0))),
2
)
for field in FOOD_FIELDS:
key = f'{field}_actual'
instance[key] = round(
instance.get(key, 0) + float(food.get(field, 0)), 2
)
return instance


def unique_food_nutrients_caclulator(daily_foods, sum_foods):
"""A function for calculating nutrients of unique food."""

for food in daily_foods:
food_entry_name = food.get('food_entry_name')
food_params = {
key: round(float(food.get(key, 0))) for key in FOOD_FIELDS
}
accumulated_food = Counter(sum_foods.get(food_entry_name))
accumulated_food.update(Counter(food_params))
sum_foods[food_entry_name] = dict(accumulated_food)
return sum_foods


def get_fatsecret_data(session, params, date):
"""A function for obtaining FatSecret user data."""

Expand Down Expand Up @@ -130,7 +122,7 @@ def get_fooddiary_objects(user, reload=False):
)

while last_diary_date <= dt.date.today():
food_entries = get_fatsecret_data(
daily_foods = get_fatsecret_data(
session=session,
params=PARAMS_FOOD_DAILY,
date=last_diary_date
Expand All @@ -142,15 +134,42 @@ def get_fooddiary_objects(user, reload=False):
date=last_diary_date
)
last_diary_month = last_diary_date.month
if food_entries:
if daily_foods:
fooddiary_objects.append(
FoodDiary(**food_caclulator(
foods=food_entries.get('food_entry'),
FoodDiary(**daily_food_caclulator(
foods=daily_foods.get('food_entry'),
weight=monthly_weights.get(last_diary_date),
project=project,
date=last_diary_date
))
)
last_diary_date += dt.timedelta(1)

session.close()
return fooddiary_objects


def get_weekly_food_nutrients(user):
"""A function for obtaining weekly foods nutrients."""

session = fatsecret.get_session(
token=(user.fatsecret_token, user.fatsecret_secret)
)
current_date = dt.date.today()
last_diary_date = current_date - dt.timedelta(7)
weekly_foods = {}

while last_diary_date < current_date:
daily_foods = get_fatsecret_data(
session=session,
params=PARAMS_FOOD_DAILY,
date=last_diary_date
)
if daily_foods:
weekly_foods = unique_food_nutrients_caclulator(
daily_foods.get('food_entry'), weekly_foods
)
last_diary_date += dt.timedelta(1)

session.close()
return weekly_foods
3 changes: 2 additions & 1 deletion blackfox/fatsecret/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@

from fatsecret.views import (
AccessTokenView, FoodDiaryDailyView, FoodDiaryMonthlyView,
RequestTokenView, WeightDiaryView,
RequestTokenView, WeeklyFoodsView, WeightDiaryView,
)

urlpatterns = [
path('request/', RequestTokenView.as_view(), name='get_request_token'),
path('access/', AccessTokenView.as_view(), name='get_access_token'),
path('weights/', WeightDiaryView.as_view(), name='weights'),
path('foods_daily/', FoodDiaryDailyView.as_view(), name='foods_daily'),
path('foods_weekly/', WeeklyFoodsView.as_view(), name='foods_weekly'),
path('foods_mothly/', FoodDiaryMonthlyView.as_view(), name='foods_monthly')
]
21 changes: 20 additions & 1 deletion blackfox/fatsecret/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from fatsecret.tools import (
BLACKFOX_URL, CALLBACK_URL, PARAMS_FOOD_DAILY, PARAMS_FOOD_MONTHLY,
PARAMS_WEIGHT, fatsecret, unix_date_converter,
PARAMS_WEIGHT, fatsecret, get_weekly_food_nutrients, unix_date_converter,
)

User = get_user_model()
Expand Down Expand Up @@ -105,3 +105,22 @@ class FoodDiaryMonthlyView(FatsecretDataView):

class WeightDiaryView(FatsecretDataView):
params = PARAMS_WEIGHT


class WeeklyFoodsView(APIView):
"""A view to aggregate weekly foods."""

def get(self, request):
if request.user.is_admin or request.user.is_coach:
user = get_object_or_404(
User, username=request.query_params.get('user')
)
else:
user = request.user
if not user.fatsecret_token or not user.fatsecret_secret:
return Response(
{'message': fatsecret_account_not_exists_message},
status=status.HTTP_400_BAD_REQUEST
)
top_weekly_foods = get_weekly_food_nutrients(user)
return Response(top_weekly_foods, status=status.HTTP_200_OK)

0 comments on commit e194533

Please sign in to comment.