Skip to content

Commit

Permalink
API: statistics by time or sport - #9
Browse files Browse the repository at this point in the history
  • Loading branch information
SamR1 committed Jun 6, 2018
1 parent 600018b commit fa4a094
Show file tree
Hide file tree
Showing 3 changed files with 850 additions and 56 deletions.
111 changes: 98 additions & 13 deletions mpwo_api/mpwo_api/activities/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,28 @@

from ..users.models import User
from ..users.utils import authenticate
from .models import Activity, convert_timedelta_to_integer
from .models import Activity, Sport, convert_timedelta_to_integer

stats_blueprint = Blueprint('stats', __name__)


@stats_blueprint.route('/stats/<int:user_id>/by_week', methods=['GET'])
@stats_blueprint.route('/stats/<int:user_id>/by_time', methods=['GET'])
@authenticate
def get_activities(auth_user_id, user_id):
def get_activities_by_time(auth_user_id, user_id):
"""Get activities statistics for a user"""
try:
user = User.query.filter_by(id=user_id).first()
if not user:
response_object = {
'status': 'fail',
'status': 'not found',
'message': 'User does not exist.'
}
return jsonify(response_object), 404

params = request.args.copy()
date_from = params.get('from')
date_to = params.get('to')
time = params.get('time')
activities_list = {}

activities = Activity.query.filter(
Expand All @@ -39,20 +40,104 @@ def get_activities(auth_user_id, user_id):
).all()

for activity in activities:
week = f'W{datetime.strftime(activity.activity_date, "%U")}' # noqa
sport = activity.sports.label
if week not in activities_list:
activities_list[week] = {}
if sport not in activities_list[week]:
activities_list[week][sport] = {
if time == 'week':
time_period = datetime.strftime(activity.activity_date, "%Y-W%U") # noqa
elif time == 'weekm': # week start Monday
time_period = datetime.strftime(activity.activity_date, "%Y-W%W") # noqa
elif time == 'month':
time_period = datetime.strftime(activity.activity_date, "%Y-%m") # noqa
elif time == 'year' or not time:
time_period = datetime.strftime(activity.activity_date, "%Y")
else:
response_object = {
'status': 'fail',
'message': 'Invalid time period.'
}
return jsonify(response_object), 400
sport_id = activity.sport_id
if time_period not in activities_list:
activities_list[time_period] = {}
if sport_id not in activities_list[time_period]:
activities_list[time_period][sport_id] = {
'nb_activities': 0,
'total_distance': 0.,
'total_duration': 0,
}
activities_list[time_period][sport_id]['nb_activities'] += 1
activities_list[time_period][sport_id]['total_distance'] += \
float(activity.distance)
activities_list[time_period][sport_id]['total_duration'] += \
convert_timedelta_to_integer(activity.duration)

response_object = {
'status': 'success',
'data': {
'statistics': activities_list
}
}
code = 200
except Exception as e:
appLog.error(e)
response_object = {
'status': 'error',
'message': 'Error. Please try again or contact the administrator.'
}
code = 500
return jsonify(response_object), code


@stats_blueprint.route('/stats/<int:user_id>/by_sport', methods=['GET'])
@authenticate
def get_activities_by_sport(auth_user_id, user_id):
"""Get activities statistics for a user"""
try:
user = User.query.filter_by(id=user_id).first()
if not user:
response_object = {
'status': 'not found',
'message': 'User does not exist.'
}
return jsonify(response_object), 404

params = request.args.copy()
date_from = params.get('from')
date_to = params.get('to')

sport_id = params.get('sport_id')
if sport_id:
sport = Sport.query.filter_by(id=sport_id).first()
if not sport:
print('not sport')
response_object = {
'status': 'not found',
'message': 'Sport does not exist.'
}
return jsonify(response_object), 404

activities = Activity.query.filter(
Activity.user_id == user_id,
Activity.activity_date >= datetime.strptime(date_from, '%Y-%m-%d')
if date_from else True,
Activity.activity_date <= datetime.strptime(date_to, '%Y-%m-%d')
if date_to else True,
Activity.sport_id == sport_id if sport_id else True,
).order_by(
Activity.activity_date.asc()
).all()

activities_list = {}
for activity in activities:
sport_id = activity.sport_id
if sport_id not in activities_list:
activities_list[sport_id] = {
'nb_activities': 0,
'total_distance': 0.,
'total_duration': 0,
}
activities_list[week][sport]['nb_activities'] += 1
activities_list[week][sport]['total_distance'] += \
activities_list[sport_id]['nb_activities'] += 1
activities_list[sport_id]['total_distance'] += \
float(activity.distance)
activities_list[week][sport]['total_duration'] += \
activities_list[sport_id]['total_duration'] += \
convert_timedelta_to_integer(activity.duration)

response_object = {
Expand Down
34 changes: 17 additions & 17 deletions mpwo_api/mpwo_api/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,63 +128,63 @@ def seven_activities_user_1():
activity = Activity(
user_id=1,
sport_id=1,
activity_date=datetime.datetime.strptime('01/01/2018', '%d/%m/%Y'),
distance=10,
activity_date=datetime.datetime.strptime('20/03/2017', '%d/%m/%Y'),
distance=5,
duration=datetime.timedelta(seconds=1024)
)
db.session.add(activity)
db.session.flush()
activity = Activity(
user_id=1,
sport_id=1,
activity_date=datetime.datetime.strptime('01/04/2018', '%d/%m/%Y'),
distance=8,
duration=datetime.timedelta(seconds=6000)
activity_date=datetime.datetime.strptime('01/06/2017', '%d/%m/%Y'),
distance=10,
duration=datetime.timedelta(seconds=3456)
)
db.session.add(activity)
db.session.flush()
activity = Activity(
user_id=1,
sport_id=1,
activity_date=datetime.datetime.strptime('20/03/2017', '%d/%m/%Y'),
distance=5,
activity_date=datetime.datetime.strptime('01/01/2018', '%d/%m/%Y'),
distance=10,
duration=datetime.timedelta(seconds=1024)
)
db.session.add(activity)
db.session.flush()
activity = Activity(
user_id=1,
sport_id=1,
activity_date=datetime.datetime.strptime('09/05/2018', '%d/%m/%Y'),
distance=10,
duration=datetime.timedelta(seconds=3000)
activity_date=datetime.datetime.strptime('23/02/2018', '%d/%m/%Y'),
distance=1,
duration=datetime.timedelta(seconds=600)
)
db.session.add(activity)
db.session.flush()
activity = Activity(
user_id=1,
sport_id=1,
activity_date=datetime.datetime.strptime('01/06/2017', '%d/%m/%Y'),
activity_date=datetime.datetime.strptime('23/02/2018', '%d/%m/%Y'),
distance=10,
duration=datetime.timedelta(seconds=3456)
duration=datetime.timedelta(seconds=1000)
)
db.session.add(activity)
db.session.flush()
activity = Activity(
user_id=1,
sport_id=1,
activity_date=datetime.datetime.strptime('23/02/2018', '%d/%m/%Y'),
distance=1,
duration=datetime.timedelta(seconds=600)
activity_date=datetime.datetime.strptime('01/04/2018', '%d/%m/%Y'),
distance=8,
duration=datetime.timedelta(seconds=6000)
)
db.session.add(activity)
db.session.flush()
activity = Activity(
user_id=1,
sport_id=1,
activity_date=datetime.datetime.strptime('23/02/2018', '%d/%m/%Y'),
activity_date=datetime.datetime.strptime('09/05/2018', '%d/%m/%Y'),
distance=10,
duration=datetime.timedelta(seconds=1000)
duration=datetime.timedelta(seconds=3000)
)
db.session.add(activity)
db.session.commit()
Expand Down
Loading

0 comments on commit fa4a094

Please sign in to comment.