Private
Public Access
1
0
This commit is contained in:
Sander Roosendaal
2022-02-17 15:16:27 +01:00
parent e9c13d3fe7
commit a547e851be
16 changed files with 133 additions and 166 deletions

View File

@@ -2,9 +2,7 @@ from rowers.models import Alert, Condition, User, Rower, Workout
from rowers.teams import coach_getcoachees from rowers.teams import coach_getcoachees
from rowers.dataprep import getsmallrowdata_db, getrowdata_db from rowers.dataprep import getsmallrowdata_db, getrowdata_db
import datetime import datetime
# BASIC operations import numpy as np
# create alert
def create_alert(manager, rower, measured, period=7, emailalert=True, def create_alert(manager, rower, measured, period=7, emailalert=True,
@@ -65,7 +63,6 @@ def alert_add_filters(alert, filters):
for f in filters: for f in filters:
metric = f['metric'] metric = f['metric']
value1 = f['value1'] value1 = f['value1']
value2 = f['value2']
condition = f['condition'] condition = f['condition']
if condition and metric and value1: if condition and metric and value1:

View File

@@ -20,7 +20,7 @@ import pytz
import iso8601 import iso8601
from matplotlib.backends.backend_agg import FigureCanvas from matplotlib.backends.backend_agg import FigureCanvas
#from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from rowsandall_app.settings import SITE_URL from rowsandall_app.settings import SITE_URL
@@ -130,7 +130,7 @@ def send_confirm(user, name, link, options): # pragma: no cover
fullemail = user.email fullemail = user.email
subject = 'New Workout Added: '+name subject = 'New Workout Added: '+name
res = send_template_email('Rowsandall <info@rowsandall.com>', _ = send_template_email('Rowsandall <info@rowsandall.com>',
[fullemail], [fullemail],
subject, 'confirmemail.html', subject, 'confirmemail.html',
d d

View File

@@ -129,7 +129,7 @@ def create_invoice(rower, amount, braintreeid, dosend=True,
if res.status_code not in [200, 201]: # pragma: no cover if res.status_code not in [200, 201]: # pragma: no cover
return 0 return 0
url = res.json()['url'] # url = res.json()['url']
id = res.json()['id'] id = res.json()['id']
urlpay = 'https://app.fakturoid.cz/api/v2/accounts/{slug}/invoices/{id}/fire.json?event=pay'.format( urlpay = 'https://app.fakturoid.cz/api/v2/accounts/{slug}/invoices/{id}/fire.json?event=pay'.format(

View File

@@ -11,7 +11,7 @@ import requests
from requests import Session, Request from requests import Session, Request
from requests_oauthlib import OAuth1, OAuth1Session from requests_oauthlib import OAuth1, OAuth1Session
from requests_oauthlib.oauth1_session import TokenRequestDenied from requests_oauthlib.oauth1_session import TokenRequestDenied
from requests import Request, Session
import rowers.mytypes as mytypes import rowers.mytypes as mytypes
from rowers.mytypes import otwtypes from rowers.mytypes import otwtypes
from rowers.rower_rules import is_workout_user, ispromember from rowers.rower_rules import is_workout_user, ispromember
@@ -35,13 +35,6 @@ from rowsandall_app.settings import (
from pytz import timezone as tz, utc from pytz import timezone as tz, utc
# You must initialize logging, otherwise you'll not see debug output.
# logging.basicConfig()
# logging.getLogger().setLevel(logging.DEBUG)
#requests_log = logging.getLogger("requests.packages.urllib3")
# requests_log.setLevel(logging.DEBUG)
#requests_log.propagate = True
from rowers.tasks import handle_get_garmin_file from rowers.tasks import handle_get_garmin_file
import django_rq import django_rq
@@ -109,9 +102,6 @@ repeattypes = {
def garmin_authorize(): # pragma: no cover def garmin_authorize(): # pragma: no cover
redirect_uri = oauth_data['redirect_uri']
client_secret = oauth_data['client_secret']
client_id = oauth_data['client_id']
base_uri = oauth_data['base_url'] base_uri = oauth_data['base_url']
garmin = OAuth1Session(oauth_data['client_id'], garmin = OAuth1Session(oauth_data['client_id'],
@@ -133,7 +123,7 @@ def garmin_processcallback(redirect_response, resource_owner_key, resource_owner
oauth_response = garmin.parse_authorization_response(redirect_response) oauth_response = garmin.parse_authorization_response(redirect_response)
verifier = oauth_response.get('oauth_verifier') verifier = oauth_response.get('oauth_verifier')
token = oauth_response.get('oauth_token') # token = oauth_response.get('oauth_token')
access_token_url = 'https://connectapi.garmin.com/oauth-service/oauth/access_token' access_token_url = 'https://connectapi.garmin.com/oauth-service/oauth/access_token'
# Using OAuth1Session # Using OAuth1Session
@@ -155,7 +145,7 @@ def garmin_processcallback(redirect_response, resource_owner_key, resource_owner
def garmin_open(user): # pragma: no cover def garmin_open(user): # pragma: no cover
r = Rower.objects.get(user=user) r = Rower.objects.get(user=user)
token = Rower.garmintoken token = r.garmintoken
if (token == '') or (token is None): if (token == '') or (token is None):
raise NoTokenError("User has no garmin token") raise NoTokenError("User has no garmin token")
@@ -191,7 +181,8 @@ def get_garmin_workout_list(user): # pragma: no cover
resource_owner_secret=r.garminrefreshtoken, resource_owner_secret=r.garminrefreshtoken,
) )
url = 'https://healthapi.garmin.com/wellness-api/rest/activities?uploadStartTimeInSeconds=1593113760&uploadEndTimeInSeconds=1593279360' url = 'https://healthapi.garmin.com/wellness-api/rest/' \
'activities?uploadStartTimeInSeconds=1593113760&uploadEndTimeInSeconds=1593279360'
result = garmin.get(url) result = garmin.get(url)
@@ -218,7 +209,7 @@ def step_to_garmin(step, order=0):
intensity = 'INTERVAL' intensity = 'INTERVAL'
except KeyError: except KeyError:
intensity = None intensity = None
#durationvaluetype = '' # durationvaluetype = ''
if durationtype == 'Time': if durationtype == 'Time':
durationtype = 'TIME' durationtype = 'TIME'
durationvalue = int(durationvalue/1000.) durationvalue = int(durationvalue/1000.)
@@ -272,11 +263,11 @@ def step_to_garmin(step, order=0):
if targetType is not None and targetType.lower() == "power": if targetType is not None and targetType.lower() == "power":
targetType = 'POWER' targetType = 'POWER'
if targetValue is not None and targetValue <= 1000: # if targetValue is not None and targetValue <= 1000:
targetValueType = 'PERCENT' # pragma: no cover # targetValueType = 'PERCENT' # pragma: no cover
else: # else:
targetValueType = None # # targetValueType = None
targetValue -= 1000 # targetValue -= 1000
try: try:
targetValueLow = step['dict']['targetValueLow'] targetValueLow = step['dict']['targetValueLow']
@@ -285,8 +276,8 @@ def step_to_garmin(step, order=0):
targetValue = None targetValue = None
elif targetValueLow == 0: # pragma: no cover elif targetValueLow == 0: # pragma: no cover
targetValueLow = None targetValueLow = None
elif targetValueLow <= 1000 and targetType == 'POWER': # pragma: no cover # elif targetValueLow <= 1000 and targetType == 'POWER': # pragma: no cover
targetValueType = 'PERCENT' # targetValueType = 'PERCENT'
elif targetValueLow > 1000 and targetType == 'POWER': # pragma: no cover elif targetValueLow > 1000 and targetType == 'POWER': # pragma: no cover
targetValueLow -= 1000 targetValueLow -= 1000
except KeyError: except KeyError:
@@ -296,8 +287,8 @@ def step_to_garmin(step, order=0):
if targetValue is not None and targetValue > 0 and targetValueHigh == 0: # pragma: no cover if targetValue is not None and targetValue > 0 and targetValueHigh == 0: # pragma: no cover
targetValueHigh = targetValue targetValueHigh = targetValue
targetValue = 0 targetValue = 0
elif targetValueHigh <= 1000 and targetType == 'POWER': # pragma: no cover # elif targetValueHigh <= 1000 and targetType == 'POWER': # pragma: no cover
targetValueType = 'PERCENT' # targetValueType = 'PERCENT'
elif targetValueHigh > 1000 and targetType == 'POWER': # pragma: no cover elif targetValueHigh > 1000 and targetType == 'POWER': # pragma: no cover
targetValueHigh -= 1000 targetValueHigh -= 1000
elif targetValueHigh == 0: # pragma: no cover elif targetValueHigh == 0: # pragma: no cover
@@ -477,12 +468,6 @@ def garmin_getworkout(garminid, r, activity):
distance = activity['distanceInMeters'] distance = activity['distanceInMeters']
except KeyError: except KeyError:
distance = 0 distance = 0
try:
averagehr = activity['averageHeartRateInBeatsPerMinute']
maxhr = activity['maxHeartRateInBeatsPerMinute']
except KeyError: # pragma: no cover
averagehr = 0
maxhr = 0
try: try:
w = Workout.objects.get(uploadedtogarmin=garminid) w = Workout.objects.get(uploadedtogarmin=garminid)
except Workout.DoesNotExist: except Workout.DoesNotExist:
@@ -494,7 +479,7 @@ def garmin_getworkout(garminid, r, activity):
utc_offset = datetime.timedelta(seconds=offset) utc_offset = datetime.timedelta(seconds=offset)
now = datetime.datetime.now(pytz.utc) now = datetime.datetime.now(pytz.utc)
zones = [tz.zone for tz in map(pytz.timezone, pytz.all_timezones_set) zones = [ttz.zone for ttz in map(pytz.timezone, pytz.all_timezones_set)
if now.astimezone(tz).utcoffset() == utc_offset] if now.astimezone(tz).utcoffset() == utc_offset]
if r.defaulttimezone in zones: # pragma: no cover if r.defaulttimezone in zones: # pragma: no cover
thetimezone = r.defaulttimezone thetimezone = r.defaulttimezone
@@ -557,12 +542,12 @@ def garmin_workouts_from_details(data):
df[' AverageBoatSpeed (m/s)'] = 0 df[' AverageBoatSpeed (m/s)'] = 0
df[' Stroke500mPace (sec/500m)'] = pace df[' Stroke500mPace (sec/500m)'] = pace
try: try:
spm = df[' Cadence (stokes/min)'] _ = df[' Cadence (stokes/min)']
except KeyError: except KeyError:
df[' Cadence (stokes/min)'] = 0 df[' Cadence (stokes/min)'] = 0
df['cum_dist'] = df[' Horizontal (meters)'] df['cum_dist'] = df[' Horizontal (meters)']
try: try:
power = df[' Power (watts)'] _ = df[' Power (watts)']
except KeyError: except KeyError:
df[' Power (watts)'] = 0 df[' Power (watts)'] = 0
df[' AverageDriveForce (lbs)'] = 0 df[' AverageDriveForce (lbs)'] = 0
@@ -591,7 +576,7 @@ def garmin_workouts_from_summaries(activities):
try: try:
r = Rower.objects.get(garmintoken=garmintoken) r = Rower.objects.get(garmintoken=garmintoken)
id = activity['summaryId'] id = activity['summaryId']
w = garmin_getworkout(id, r, activity) _ = garmin_getworkout(id, r, activity)
except Rower.DoesNotExist: # pragma: no cover except Rower.DoesNotExist: # pragma: no cover
pass pass

View File

@@ -1,4 +1,5 @@
import pandas as pd import pandas as pd
import numpy as np
import datetime import datetime
from datetime import timedelta from datetime import timedelta
from uuid import uuid4 from uuid import uuid4
@@ -52,14 +53,14 @@ def add_workout_from_data(userid, nkid, data, strokedata, source='nk', splitdata
elapsedTime = data["elapsedTime"] elapsedTime = data["elapsedTime"]
totalDistanceGps = data["totalDistanceGps"] totalDistanceGps = data["totalDistanceGps"]
totalDistanceImp = data["totalDistanceImp"] totalDistanceImp = data["totalDistanceImp"]
intervals = data["intervals"] # add intervals # intervals = data["intervals"] # add intervals
oarlockSessions = data["oarlockSessions"] oarlockSessions = data["oarlockSessions"]
deviceId = data["deviceId"] # you could get the firmware version # deviceId = data["deviceId"] # you could get the firmware version
totalDistance = totalDistanceGps totalDistance = totalDistanceGps
useImpeller = False useImpeller = False
if speedInput: # pragma: no cover if speedInput: # pragma: no cover
totdalDistance = totalDistanceImp totalDistance = totalDistanceImp
useImpeller = True useImpeller = True
summary = get_nk_allstats(data, strokedata) summary = get_nk_allstats(data, strokedata)
@@ -69,19 +70,19 @@ def add_workout_from_data(userid, nkid, data, strokedata, source='nk', splitdata
# oarlock inboard, length, boat name # oarlock inboard, length, boat name
if oarlockSessions: if oarlockSessions:
oarlocksession = oarlockSessions[0] # should take seatIndex oarlocksession = oarlockSessions[0] # should take seatIndex
boatName = oarlocksession["boatName"] # boatName = oarlocksession["boatName"]
oarLength = oarlocksession["oarLength"] # cm oarLength = oarlocksession["oarLength"] # cm
oarInboardLength = oarlocksession["oarInboardLength"] # cm oarInboardLength = oarlocksession["oarInboardLength"] # cm
seatNumber = oarlocksession["seatNumber"] # seatNumber = oarlocksession["seatNumber"]
try: try:
oarlockfirmware = oarlocksession["firmwareVersion"] oarlockfirmware = oarlocksession["firmwareVersion"]
except KeyError: except KeyError:
oarlockfirmware = '' oarlockfirmware = ''
else: # pragma: no cover else: # pragma: no cover
boatName = '' # boatName = ''
oarLength = 289 oarLength = 289
oarInboardLength = 88 oarInboardLength = 88
seatNumber = 1 # seatNumber = 1
oarlockfirmware = '' oarlockfirmware = ''
workouttype = "water" workouttype = "water"
@@ -139,7 +140,7 @@ def get_nk_intervalstats(workoutdata, strokedata):
i = 0 i = 0
for interval in intervals: for interval in intervals:
id = interval['id'] # id = interval['id']
sdist = interval['totalDistanceGps'] sdist = interval['totalDistanceGps']
avgpace = interval['avgPaceGps']/1000. avgpace = interval['avgPaceGps']/1000.
avgpacetd = timedelta(seconds=avgpace) avgpacetd = timedelta(seconds=avgpace)
@@ -325,6 +326,6 @@ def readlogs_summaries(logfile, dosave=0): # pragma: no cover
json.dump(strokeData, f2) json.dump(strokeData, f2)
with open(filename2, 'w') as f2: with open(filename2, 'w') as f2:
json.dump(summaryData, f2) json.dump(summaryData, f2)
except Exception as e: except Exception:
print(traceback.format_exc()) print(traceback.format_exc())
print("error") print("error")

View File

@@ -31,13 +31,6 @@ queue = django_rq.get_queue('default')
queuelow = django_rq.get_queue('low') queuelow = django_rq.get_queue('low')
queuehigh = django_rq.get_queue('low') queuehigh = django_rq.get_queue('low')
try:
from json.decoder import JSONDecodeError
except ImportError: # pragma: no cover
JSONDecodeError = ValueError
oauth_data = { oauth_data = {
'client_id': NK_CLIENT_ID, 'client_id': NK_CLIENT_ID,
'client_secret': NK_CLIENT_SECRET, 'client_secret': NK_CLIENT_SECRET,
@@ -56,12 +49,6 @@ oauth_data = {
def get_token(code): # pragma: no cover def get_token(code): # pragma: no cover
url = oauth_data['base_url'] url = oauth_data['base_url']
headers = {'Accept': 'application/json',
# 'Authorization': auth_header,
'Content-Type': 'application/x-www-form-urlencoded',
# 'user-agent': 'sanderroosendaal'
}
post_data = {"client_id": oauth_data['client_id'], post_data = {"client_id": oauth_data['client_id'],
"grant_type": "authorization_code", "grant_type": "authorization_code",
"redirect_uri": oauth_data['redirect_uri'], "redirect_uri": oauth_data['redirect_uri'],
@@ -88,13 +75,12 @@ def nk_open(user):
r = Rower.objects.get(user=user) r = Rower.objects.get(user=user)
if (r.nktoken == '') or (r.nktoken is None): # pragma: no cover if (r.nktoken == '') or (r.nktoken is None): # pragma: no cover
s = "Token doesn't exist. Need to authorize"
raise NoTokenError("User has no token") raise NoTokenError("User has no token")
else: else:
if (timezone.now() > r.nktokenexpirydate): if (timezone.now() > r.nktokenexpirydate):
thetoken = rower_nk_token_refresh(user) thetoken = rower_nk_token_refresh(user)
if thetoken == None: # pragma: no cover if thetoken is None: # pragma: no cover
raise NoTokenError("User has no token") raise NoTokenError("User has no token")
return thetoken return thetoken
else: else:
@@ -105,7 +91,7 @@ def nk_open(user):
def get_nk_workouts(rower, do_async=True, before=0, after=0): def get_nk_workouts(rower, do_async=True, before=0, after=0):
try: try:
thetoken = nk_open(rower.user) _ = nk_open(rower.user)
except NoTokenError: # pragma: no cover except NoTokenError: # pragma: no cover
return 0 return 0
@@ -136,7 +122,7 @@ def get_nk_workouts(rower, do_async=True, before=0, after=0):
pass pass
knownnkids = uniqify(knownnkids+tombstones+parkedids) knownnkids = uniqify(knownnkids+tombstones+parkedids)
newids = [nkid for nkid in nkids if not nkid in knownnkids] newids = [nkid for nkid in nkids if nkid not in knownnkids]
s = 'New NK IDs {newids}'.format(newids=newids) s = 'New NK IDs {newids}'.format(newids=newids)
dologging('nklog.log', s) dologging('nklog.log', s)
@@ -211,7 +197,8 @@ def get_nk_workout_list(user, fake=False, after=0, before=0):
if (r.nktoken == '') or (r.nktoken is None): # pragma: no cover if (r.nktoken == '') or (r.nktoken is None): # pragma: no cover
s = "Token doesn't exist. Need to authorize" s = "Token doesn't exist. Need to authorize"
return custom_exception_handler(401, s) return custom_exception_handler(401, s)
elif (r.nktokenexpirydate is None or timezone.now()+timedelta(seconds=10) > r.nktokenexpirydate): # pragma: no cover elif (r.nktokenexpirydate is None or
timezone.now()+timedelta(seconds=10) > r.nktokenexpirydate): # pragma: no cover
s = "Token expired. Needs to refresh." s = "Token expired. Needs to refresh."
return custom_exception_handler(401, s) return custom_exception_handler(401, s)
else: else:
@@ -251,10 +238,6 @@ def get_workout(user, nkid, do_async=True, startdate='', enddate=''):
s = "Token expired. Needs to refresh." s = "Token expired. Needs to refresh."
return custom_exception_handler(401, s), 0 return custom_exception_handler(401, s), 0
params = {
'sessionIds': nkid,
}
before = 0 before = 0
after = 0 after = 0
if startdate: # pragma: no cover if startdate: # pragma: no cover

View File

@@ -7,7 +7,7 @@ import requests
import requests.auth import requests.auth
import json import json
from django.utils import timezone from django.utils import timezone
from datetime import datetime from datetime import datetime, timedelta
import numpy as np import numpy as np
from dateutil import parser from dateutil import parser
import time import time
@@ -30,7 +30,10 @@ from rowingdata import rowingdata
import pandas as pd import pandas as pd
from rowers.models import Rower, Workout from rowers.models import Rower, Workout
from rowsandall_app.settings import C2_CLIENT_ID, C2_REDIRECT_URI, C2_CLIENT_SECRET, STRAVA_CLIENT_ID, STRAVA_REDIRECT_URI, STRAVA_CLIENT_SECRET, SPORTTRACKS_CLIENT_SECRET, SPORTTRACKS_CLIENT_ID, SPORTTRACKS_REDIRECT_URI from rowsandall_app.settings import (
C2_CLIENT_ID, C2_REDIRECT_URI, C2_CLIENT_SECRET,
STRAVA_CLIENT_ID, STRAVA_REDIRECT_URI, STRAVA_CLIENT_SECRET,
SPORTTRACKS_CLIENT_SECRET, SPORTTRACKS_CLIENT_ID, SPORTTRACKS_REDIRECT_URI)
TEST_CLIENT_ID = "1" TEST_CLIENT_ID = "1"
TEST_CLIENT_SECRET = "aapnootmies" TEST_CLIENT_SECRET = "aapnootmies"
@@ -57,8 +60,8 @@ def custom_exception_handler(exc, message): # pragma: no cover
def do_refresh_token(refreshtoken): # pragma: no cover def do_refresh_token(refreshtoken): # pragma: no cover
client_auth = requests.auth.HTTPBasicAuth( # client_auth = requests.auth.HTTPBasicAuth(
TEST_CLIENT_ID, TEST_CLIENT_SECRET) # TEST_CLIENT_ID, TEST_CLIENT_SECRET)
post_data = {"grant_type": "refresh_token", post_data = {"grant_type": "refresh_token",
"client_secret": TEST_CLIENT_SECRET, "client_secret": TEST_CLIENT_SECRET,
"client_id": TEST_CLIENT_ID, "client_id": TEST_CLIENT_ID,
@@ -86,8 +89,8 @@ def do_refresh_token(refreshtoken): # pragma: no cover
def get_token(code): # pragma: no cover def get_token(code): # pragma: no cover
client_auth = requests.auth.HTTPBasicAuth( # client_auth = requests.auth.HTTPBasicAuth(
TEST_CLIENT_ID, TEST_CLIENT_SECRET) # TEST_CLIENT_ID, TEST_CLIENT_SECRET)
post_data = {"grant_type": "authorization_code", post_data = {"grant_type": "authorization_code",
"code": code, "code": code,
"redirect_uri": "http://localhost:8000/rowers/test_callback", "redirect_uri": "http://localhost:8000/rowers/test_callback",
@@ -123,7 +126,6 @@ def make_authorization_url(request): # pragma: no cover
"scope": "write", "scope": "write",
"state": state} "state": state}
import urllib
url = "http://localhost:8000/rowers/o/authorize" + \ url = "http://localhost:8000/rowers/o/authorize" + \
urllib.parse.urlencode(params) urllib.parse.urlencode(params)
@@ -170,8 +172,8 @@ def get_ownapi_workout_list(user): # pragma: no cover
def get_ownapi_workout(user, ownapiid): # pragma: no cover def get_ownapi_workout(user, ownapiid): # pragma: no cover
r = Rower.objects.get(user=user) r = Rower.objects.get(user=user)
if (r.ownapitoken == '') or (r.ownapitoken is None): if (r.ownapitoken == '') or (r.ownapitoken is None):
return custom_exception_handler(401, s)
s = "Token doesn't exist. Need to authorize" s = "Token doesn't exist. Need to authorize"
return custom_exception_handler(401, s)
elif (timezone.now() > r.ownapitokenexpirydate): elif (timezone.now() > r.ownapitokenexpirydate):
s = "Token expired. Needs to refresh." s = "Token expired. Needs to refresh."
return custom_exception_handler(401, s) return custom_exception_handler(401, s)

View File

@@ -76,8 +76,8 @@ def mkplot(row, title):
ax1.set_title(title) ax1.set_title(title)
plt.grid(True) plt.grid(True)
majorFormatter = FuncFormatter(format_pace_tick) majorFormatter = FuncFormatter(format_pace_tick)
majorLocator = (5) # majorLocator = (5)
timeTickFormatter = NullFormatter() # timeTickFormatter = NullFormatter()
ax1.yaxis.set_major_formatter(majorFormatter) ax1.yaxis.set_major_formatter(majorFormatter)
@@ -88,7 +88,7 @@ def mkplot(row, title):
ax2.plot(t, hr, 'r-') ax2.plot(t, hr, 'r-')
ax2.set_ylabel('Heart Rate', color='r') ax2.set_ylabel('Heart Rate', color='r')
majorTimeFormatter = FuncFormatter(format_time_tick) majorTimeFormatter = FuncFormatter(format_time_tick)
majorLocator = (15*60) # majorLocator = (15*60)
ax2.xaxis.set_major_formatter(majorTimeFormatter) ax2.xaxis.set_major_formatter(majorTimeFormatter)
ax2.patch.set_alpha(0.0) ax2.patch.set_alpha(0.0)
for tl in ax2.get_yticklabels(): for tl in ax2.get_yticklabels():

View File

@@ -57,8 +57,6 @@ queuehigh = django_rq.get_queue('high')
# Project # Project
# from .models import Profile # from .models import Profile
#baseurl = 'https://polaraccesslink.com/v3-example'
baseurl = 'https://polaraccesslink.com/v3' baseurl = 'https://polaraccesslink.com/v3'
@@ -125,7 +123,7 @@ def get_token(code):
def make_authorization_url(): # pragma: no cover def make_authorization_url(): # pragma: no cover
# Generate a random string for the state parameter # Generate a random string for the state parameter
# Save it for use later to prevent xsrf attacks # Save it for use later to prevent xsrf attacks
state = str(uuid4()) # state = str(uuid4())
params = {"client_id": POLAR_CLIENT_ID, params = {"client_id": POLAR_CLIENT_ID,
"response_type": "code", "response_type": "code",
@@ -155,7 +153,7 @@ def revoke_access(user): # pragma: no cover
def get_polar_notifications(): def get_polar_notifications():
url = baseurl+'/notifications' url = baseurl+'/notifications'
state = str(uuid4()) # state = str(uuid4())
auth_string = '{id}:{secret}'.format( auth_string = '{id}:{secret}'.format(
id=POLAR_CLIENT_ID, id=POLAR_CLIENT_ID,
secret=POLAR_CLIENT_SECRET secret=POLAR_CLIENT_SECRET
@@ -302,16 +300,12 @@ def get_polar_workouts(user):
'title': '', 'title': '',
} }
#session = requests.session()
#newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}
# session.headers.update(newHeaders)
url = settings.UPLOAD_SERVICE_URL url = settings.UPLOAD_SERVICE_URL
dologging('polar.log', uploadoptions) dologging('polar.log', uploadoptions)
dologging('polar.log', url) dologging('polar.log', url)
#response = session.post(url,json=uploadoptions)
job = myqueue( _ = myqueue(
queuehigh, queuehigh,
handle_request_post, handle_request_post,
url, url,
@@ -381,9 +375,6 @@ def register_user(user, token):
json=payload, json=payload,
headers=headers headers=headers
) )
#url = baseurl+'/users'
#response = requests.post(url,params=params,headers=headers)
if response.status_code not in [200, 201]: # pragma: no cover if response.status_code not in [200, 201]: # pragma: no cover
# dologging('polar.log',url) # dologging('polar.log',url)
@@ -419,10 +410,6 @@ def get_polar_user_info(user, physical=False): # pragma: no cover
'Accept': 'application/json' 'Accept': 'application/json'
} }
params = {
'user-id': r.polaruserid
}
if not physical: if not physical:
url = baseurl+'/users/{userid}'.format( url = baseurl+'/users/{userid}'.format(
userid=r.polaruserid userid=r.polaruserid
@@ -478,11 +465,11 @@ def get_polar_workout(user, id, transactionid):
exercise_dict = response.json() exercise_dict = response.json()
thisid = exercise_dict['id'] thisid = exercise_dict['id']
if thisid == id: if thisid == id:
url = baseurl+'/users/{userid}/exercise-transactions/{transactionid}/exercises/{exerciseid}/tcx'.format( url = baseurl+'/users/{userid}/exercise-transactions/{transactionid}' \
'/exercises/{exerciseid}/tcx'.format(
userid=r.polaruserid, userid=r.polaruserid,
transactionid=transactionid, transactionid=transactionid,
exerciseid=id exerciseid=id)
)
authorizationstring = str('Bearer ' + r.polartoken) authorizationstring = str('Bearer ' + r.polartoken)
headers2 = { headers2 = {
'Authorization': authorizationstring, 'Authorization': authorizationstring,

View File

@@ -19,7 +19,18 @@ DESCRIPTOR = _descriptor.FileDescriptor(
package='rowing_workout_metrics', package='rowing_workout_metrics',
syntax='proto3', syntax='proto3',
serialized_options=None, serialized_options=None,
serialized_pb=_b('\n\x1crowing-workout-metrics.proto\x12\x16rowing_workout_metrics\"p\n\x15WorkoutMetricsRequest\x12\x10\n\x08\x66ilename\x18\x01 \x01(\t\x12\x0b\n\x03sex\x18\x02 \x01(\t\x12\x0b\n\x03\x66tp\x18\x03 \x01(\x01\x12\r\n\x05hrftp\x18\x04 \x01(\x01\x12\r\n\x05hrmax\x18\x05 \x01(\x01\x12\r\n\x05hrmin\x18\x06 \x01(\x01\"p\n\x16WorkoutMetricsResponse\x12\x0b\n\x03tss\x18\x01 \x01(\x01\x12\r\n\x05normp\x18\x02 \x01(\x01\x12\r\n\x05trimp\x18\x03 \x01(\x01\x12\r\n\x05hrtss\x18\x04 \x01(\x01\x12\r\n\x05normv\x18\x05 \x01(\x01\x12\r\n\x05normw\x18\x06 \x01(\x01\x32w\n\x07Metrics\x12l\n\x0b\x43\x61lcMetrics\x12-.rowing_workout_metrics.WorkoutMetricsRequest\x1a..rowing_workout_metrics.WorkoutMetricsResponseb\x06proto3') serialized_pb=_b('\n\x1crowing-workout-metrics.proto\x12\x16'
'rowing_workout_metrics\"p\n\x15WorkoutMetricsRequest'
'\x12\x10\n\x08\x66ilename'
'\x18\x01 \x01(\t\x12\x0b\n\x03sex'
'\x18\x02 \x01(\t\x12\x0b\n\x03\x66tp\x18\x03 \x01'
'(\x01\x12\r\n\x05hrftp\x18\x04 \x01(\x01\x12\r\n\x05hrmax'
'\x18\x05 \x01(\x01\x12\r\n\x05hrmin\x18\x06 \x01(\x01\"p\n\x16WorkoutMetricsResponse'
'\x12\x0b\n\x03tss\x18\x01 \x01(\x01\x12\r\n\x05normp\x18\x02 \x01(\x01\x12\r\n\x05trimp'
'\x18\x03 \x01(\x01\x12\r\n\x05hrtss\x18\x04 \x01(\x01\x12\r\n\x05normv'
'\x18\x05 \x01(\x01\x12\r\n\x05normw\x18\x06 \x01(\x01\x32w\n\x07Metrics'
'\x12l\n\x0b\x43\x61lcMetrics\x12-.rowing_workout_metrics.WorkoutMetricsRequest'
'\x1a..rowing_workout_metrics.WorkoutMetricsResponseb\x06proto3')
) )

View File

@@ -6,7 +6,7 @@ from rest_framework import serializers
from rowers.models import ( from rowers.models import (
Workout, Rower, FavoriteChart, VirtualRaceResult, Workout, Rower, FavoriteChart, VirtualRaceResult,
VirtualRace, GeoCourse, StandardCollection, CourseStandard, VirtualRace, GeoCourse, StandardCollection, CourseStandard,
GeoCourse, GeoPolygon, GeoPoint, PlannedSession, GeoPolygon, GeoPoint, PlannedSession,
) )
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied

View File

@@ -7,6 +7,8 @@ import time
import os import os
import sys import sys
import django import django
from django.contrib import messages
proj_path = "../" proj_path = "../"
sys.path.append(proj_path) sys.path.append(proj_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rowsandall_app.settings") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rowsandall_app.settings")
@@ -15,11 +17,7 @@ django.setup()
@app.task @app.task
def addcomment2(userid, id, debug=False): def addcomment2(userid, id, debug=False):
time.sleep(5) time.sleep(5)
# w = Workout.objects.get(id=id)
# w.notes += '\n the task has run'
# w.save()
u = User.objects.get(id=userid) u = User.objects.get(id=userid)
messages.info(u, ' The task has run') messages.info(u, ' The task has run')
messages.error(u, ' Het is veel te laat') messages.error(u, ' Het is veel te laat')

View File

@@ -151,8 +151,6 @@ class TraverseLinksTest(TestCase):
if response.status_code == 200: if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser') soup = BeautifulSoup(response.content, 'html.parser')
text = soup.get_text()
for link in soup.find_all('a'): for link in soup.find_all('a'):
new_link = link.get('href') new_link = link.get('href')
if VERBOSE: if VERBOSE:

View File

@@ -17,7 +17,6 @@ from rest_framework.permissions import *
from rowers import views from rowers import views
from django.contrib.auth import views as auth_views from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView from django.views.generic.base import TemplateView
from django.utils.decorators import method_decorator
from rowers.permissions import ( from rowers.permissions import (
IsOwnerOrNot, IsOwnerOrReadOnly, IsOwnerOrNot, IsOwnerOrReadOnly,
@@ -71,7 +70,7 @@ class PlannedSessionViewSet(viewsets.ModelViewSet):
class WorkoutViewSet(viewsets.ModelViewSet): class WorkoutViewSet(viewsets.ModelViewSet):
model = Workout model = Workout
#queryset = Workout.objects.all().order_by("-date", "-starttime")
serializer_class = WorkoutSerializer serializer_class = WorkoutSerializer
def get_queryset(self): # pragma: no cover def get_queryset(self): # pragma: no cover
@@ -90,7 +89,6 @@ class WorkoutViewSet(viewsets.ModelViewSet):
class RowerViewSet(viewsets.ModelViewSet): class RowerViewSet(viewsets.ModelViewSet):
model = Rower model = Rower
serializer_class = RowerSerializer serializer_class = RowerSerializer
#queryset = Rower.objects.all()
def get_queryset(self): # pragma: no cover def get_queryset(self): # pragma: no cover
try: try:
@@ -109,7 +107,6 @@ class RowerViewSet(viewsets.ModelViewSet):
class FavoriteChartViewSet(viewsets.ModelViewSet): class FavoriteChartViewSet(viewsets.ModelViewSet):
model = FavoriteChart model = FavoriteChart
serializer_class = FavoriteChartSerializer serializer_class = FavoriteChartSerializer
#queryset = FavoriteChart.objects.all()
def get_queryset(self): # pragma: no cover def get_queryset(self): # pragma: no cover
try: try:
@@ -235,8 +232,6 @@ handler400 = views.error400_view
handler500 = views.error500_view handler500 = views.error500_view
#app_name = "rowers"
urlpatterns = [ urlpatterns = [
re_path(r'^o/authorize/$', base.AuthorizationView.as_view(), name="authorize"), re_path(r'^o/authorize/$', base.AuthorizationView.as_view(), name="authorize"),
re_path(r'^o/token/$', base.TokenView.as_view(), name="token"), re_path(r'^o/token/$', base.TokenView.as_view(), name="token"),
@@ -352,17 +347,21 @@ urlpatterns = [
re_path(r'^workouts-join-select/user/(?P<userid>\d+)/$', re_path(r'^workouts-join-select/user/(?P<userid>\d+)/$',
views.workouts_join_select, name='workouts_join_select'), views.workouts_join_select, name='workouts_join_select'),
re_path( re_path(
r'^user-analysis-select/(?P<function>\w.*)/team/(?P<teamid>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.analysis_new, name='analysis_new'), r'^user-analysis-select/(?P<function>\w.*)/team/(?P<teamid>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$',
views.analysis_new, name='analysis_new'),
re_path( re_path(
r'^user-analysis-select/(?P<function>\w.*)/session/(?P<session>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.analysis_new, name='analysis_new'), r'^user-analysis-select/(?P<function>\w.*)/session/(?P<session>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$',
views.analysis_new, name='analysis_new'),
re_path( re_path(
r'^user-analysis-select/(?P<function>\w.*)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.analysis_new, name='analysis_new'), r'^user-analysis-select/(?P<function>\w.*)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$',
views.analysis_new, name='analysis_new'),
re_path(r'^user-analysis-select/(?P<function>\w.*)/user/(?P<userid>\d+)/$', re_path(r'^user-analysis-select/(?P<function>\w.*)/user/(?P<userid>\d+)/$',
views.analysis_new, name='analysis_new'), views.analysis_new, name='analysis_new'),
re_path(r'^user-analysis-select/(?P<function>\w.*)/team/(?P<teamid>\d+)/$', re_path(r'^user-analysis-select/(?P<function>\w.*)/team/(?P<teamid>\d+)/$',
views.analysis_new, name='analysis_new'), views.analysis_new, name='analysis_new'),
re_path( re_path(
r'^user-analysis-select/team/(?P<teamid>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.analysis_new, name='analysis_new'), r'^user-analysis-select/team/(?P<teamid>\d+)/workout/(?P<id>\b[0-9A-Fa-f]+\b)/$',
views.analysis_new, name='analysis_new'),
re_path(r'^user-analysis-select/user/(?P<userid>\d+)/$', re_path(r'^user-analysis-select/user/(?P<userid>\d+)/$',
views.analysis_new, name='analysis_new'), views.analysis_new, name='analysis_new'),
re_path(r'^user-analysis-select/team/(?P<teamid>\d+)/$', re_path(r'^user-analysis-select/team/(?P<teamid>\d+)/$',
@@ -613,7 +612,8 @@ urlpatterns = [
views.workout_nkimport_view, name='workout_nkimport_view'), views.workout_nkimport_view, name='workout_nkimport_view'),
re_path(r'^workout/nkimport/all/$', views.workout_getnkworkout_all, re_path(r'^workout/nkimport/all/$', views.workout_getnkworkout_all,
name='workout_getnkworkout_all'), name='workout_getnkworkout_all'),
re_path(r'^workout/nkimport/all/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$', views.workout_getnkworkout_all, re_path(r'^workout/nkimport/all/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$',
views.workout_getnkworkout_all,
name='workout_getnkworkout_all'), name='workout_getnkworkout_all'),
re_path(r'^workout/rp3import/(?P<externalid>\d+)/$', views.workout_getrp3importview, re_path(r'^workout/rp3import/(?P<externalid>\d+)/$', views.workout_getrp3importview,
name='workout_getrp3importview'), name='workout_getrp3importview'),
@@ -853,11 +853,15 @@ urlpatterns = [
name='workout_workflow_view'), name='workout_workflow_view'),
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/courses/$', views.workout_course_view, re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/courses/$', views.workout_course_view,
name='workout_course_view'), name='workout_course_view'),
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/(?P<xparam>[\w\ ]+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/(?P<plottype>\w+)/$', re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/'\
'(?P<xparam>[\w\ ]+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/(?P<plottype>\w+)/$',
views.workout_flexchart3_view, name='workout_flexchart3_view'), views.workout_flexchart3_view, name='workout_flexchart3_view'),
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/(?P<xparam>\w+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/(?P<plottype>\w+.*)/$', re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/'\
'(?P<xparam>\w+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/(?P<plottype>\w+.*)/$',
views.workout_flexchart3_view, name='workout_flexchart3_view'), views.workout_flexchart3_view, name='workout_flexchart3_view'),
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/(?P<xparam>\w+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/$', re_path(
r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/'\
'(?P<xparam>\w+.*)/(?P<yparam1>[\w\ ]+.*)/(?P<yparam2>[\w\ ]+.*)/$',
views.workout_flexchart3_view, name='workout_flexchart3_view'), views.workout_flexchart3_view, name='workout_flexchart3_view'),
re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/$', re_path(r'^workout/(?P<id>\b[0-9A-Fa-f]+\b)/flexchart/$',
views.workout_flexchart3_view, name='workout_flexchart3_view'), views.workout_flexchart3_view, name='workout_flexchart3_view'),
@@ -1002,7 +1006,8 @@ urlpatterns = [
name='plannedsession_teamclone_view'), name='plannedsession_teamclone_view'),
re_path(r'^sessions/(?P<id>\d+)/clone/$', views.plannedsession_clone_view), re_path(r'^sessions/(?P<id>\d+)/clone/$', views.plannedsession_clone_view),
re_path( re_path(
r'^sessions/(?P<psid>\d+)/detach/(?P<id>\b[0-9A-Fa-f]+\b)/user/(?P<userid>\d+)/$', views.plannedsession_detach_view), r'^sessions/(?P<psid>\d+)/detach/(?P<id>\b[0-9A-Fa-f]+\b)/user/(?P<userid>\d+)/$',
views.plannedsession_detach_view),
re_path( re_path(
r'^sessions/(?P<psid>\d+)/detach/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.plannedsession_detach_view), r'^sessions/(?P<psid>\d+)/detach/(?P<id>\b[0-9A-Fa-f]+\b)/$', views.plannedsession_detach_view),
re_path(r'^sessions/(?P<id>\d+)/$', views.plannedsession_view, re_path(r'^sessions/(?P<id>\d+)/$', views.plannedsession_view,
@@ -1043,7 +1048,8 @@ urlpatterns = [
name='plannedsessions_print_view'), name='plannedsessions_print_view'),
re_path(r'^sessions/(?P<id>\d+)/message/$', views.plannedsession_message_view, re_path(r'^sessions/(?P<id>\d+)/message/$', views.plannedsession_message_view,
name='plannedsession_message_view'), name='plannedsession_message_view'),
re_path(r'^sessions/print/user/(?P<userid>\d+)/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$', views.plannedsessions_print_view, re_path(r'^sessions/print/user/(?P<userid>\d+)/(?P<startdatestring>\d+-\d+-\d+)/(?P<enddatestring>\d+-\d+-\d+)/$',
views.plannedsessions_print_view,
name='plannedsessions_print_view'), name='plannedsessions_print_view'),
re_path(r'^sessions/sendcalendar/$', views.plannedsessions_icsemail_view, re_path(r'^sessions/sendcalendar/$', views.plannedsessions_icsemail_view,
name='plannedsessions_coach_icsemail_view'), name='plannedsessions_coach_icsemail_view'),

View File

@@ -16,14 +16,11 @@ import datetime
import json import json
import time import time
from fitparse import FitFile from fitparse import FitFile
from django.conf import settings
from django.http import HttpResponse from django.http import HttpResponse
import requests import requests
from django.http import HttpResponse
import humanize import humanize
from pytz.exceptions import UnknownTimeZoneError from pytz.exceptions import UnknownTimeZoneError
import pytz import pytz
@@ -189,7 +186,6 @@ palettes = {
'gold_sunset': (47, -31, .26, -0.12, 0.94, -0.5), 'gold_sunset': (47, -31, .26, -0.12, 0.94, -0.5),
'blue_red': (207, -200, .85, 0, .74, -.24), 'blue_red': (207, -200, .85, 0, .74, -.24),
'blue_green': (207, -120, .85, 0, .75, .25), 'blue_green': (207, -120, .85, 0, .75, .25),
'cyan_green': (192, -50, .08, .65, .98, -.34),
'cyan_purple': trcolors(237, 248, 251, 136, 65, 157), 'cyan_purple': trcolors(237, 248, 251, 136, 65, 157),
'green_blue': trcolors(240, 249, 232, 8, 104, 172), 'green_blue': trcolors(240, 249, 232, 8, 104, 172),
'orange_red': trcolors(254, 240, 217, 179, 0, 0), 'orange_red': trcolors(254, 240, 217, 179, 0, 0),
@@ -237,7 +233,8 @@ def str2bool(v): # pragma: no cover
def uniqify(seq, idfun=None): def uniqify(seq, idfun=None):
# order preserving # order preserving
if idfun is None: if idfun is None:
def idfun(x): return x def idfun(x):
return x
seen = {} seen = {}
result = [] result = []
for item in seq: for item in seq:
@@ -465,14 +462,14 @@ def totaltime_sec_to_string(totaltime, shorten=False):
hours=hours, hours=hours,
minutes=minutes, minutes=minutes,
seconds=seconds, seconds=seconds,
tenths=tenths # tenths=tenths
) )
else: else:
duration = "{minutes}:{seconds:02d}".format( duration = "{minutes}:{seconds:02d}".format(
hours=hours, # hours=hours,
minutes=minutes, minutes=minutes,
seconds=seconds, seconds=seconds,
tenths=tenths # tenths=tenths
) )
return duration return duration
@@ -559,12 +556,12 @@ def get_strava_stream(r, metric, stravaid, series_type='time', fetchresolution='
if metric == 'power': # pragma: no cover if metric == 'power': # pragma: no cover
metric = 'watts' metric = 'watts'
url = "https://www.strava.com/api/v3/activities/{stravaid}/streams/{metric}?resolution={fetchresolution}&series_type={series_type}".format( url = "https://www.strava.com/api/v3/activities/{stravaid}" \
"/streams/{metric}?resolution={fetchresolution}&series_type={series_type}".format(
stravaid=stravaid, stravaid=stravaid,
fetchresolution=fetchresolution, fetchresolution=fetchresolution,
series_type=series_type, series_type=series_type,
metric=metric metric=metric)
)
s = requests.get(url, headers=headers) s = requests.get(url, headers=headers)
@@ -574,7 +571,6 @@ def get_strava_stream(r, metric, stravaid, series_type='time', fetchresolution='
try: try:
for data in s.json(): for data in s.json():
y = None
try: try:
if data['type'] == metric: if data['type'] == metric:
return np.array(data['data']) return np.array(data['data'])
@@ -790,14 +786,14 @@ def get_step_type(step): # pragma: no cover
return t return t
def peel(l): def peel(listToPeel):
if len(l) == 0: # pragma: no cover if len(listToPeel) == 0: # pragma: no cover
return None, None return None, None
if len(l) == 1: if len(listToPeel) == 1:
return l[0], None return listToPeel[0], None
first = l[0] first = listToPeel[0]
rest = l[1:] rest = listToPeel[1:]
if first['type'] == 'Step': # pragma: no cover if first['type'] == 'Step': # pragma: no cover
return first, rest return first, rest
@@ -944,7 +940,7 @@ def step_to_string(step, short=False):
repeatValue = 1 repeatValue = 1
nr = 0 nr = 0
name = ''
intensity = '' intensity = ''
duration = '' duration = ''
unit = '' unit = ''
@@ -954,7 +950,11 @@ def step_to_string(step, short=False):
durationtype = step['durationType'] durationtype = step['durationType']
if step['durationValue'] == 0: if step['durationValue'] == 0:
if durationtype not in ['RepeatUntilStepsCmplt', 'RepeatUntilHrLessThan', 'RepeatUntilHrGreaterThan']: # pragma: no cover if durationtype not in [
'RepeatUntilStepsCmplt',
'RepeatUntilHrLessThan',
'RepeatUntilHrGreaterThan'
]: # pragma: no cover
return '', type, -1, -1, 1 return '', type, -1, -1, 1
if durationtype == 'Time': if durationtype == 'Time':
@@ -963,7 +963,6 @@ def step_to_string(step, short=False):
if value/1000. >= 3600: # pragma: no cover if value/1000. >= 3600: # pragma: no cover
unit = 'h' unit = 'h'
dd = timedelta(seconds=value/1000.) dd = timedelta(seconds=value/1000.)
#duration = humanize.naturaldelta(dd, minimum_unit="seconds")
duration = '{v}'.format(v=str(dd)) duration = '{v}'.format(v=str(dd))
elif durationtype == 'Distance': elif durationtype == 'Distance':
unit = 'm' unit = 'm'
@@ -1163,7 +1162,7 @@ def step_to_string(step, short=False):
nr = step['stepId'] nr = step['stepId']
name = step['wkt_step_name'] # name = step['wkt_step_name']
notes = '' notes = ''
try: try:
@@ -1178,10 +1177,10 @@ def step_to_string(step, short=False):
intensity = 0 intensity = 0
s = '{duration} {unit} {target} {repeat} {notes}'.format( s = '{duration} {unit} {target} {repeat} {notes}'.format(
nr=nr, # nr=nr,
name=name, # name=name,
unit=unit, unit=unit,
intensity=intensity, # intensity=intensity,
duration=duration, duration=duration,
target=target, target=target,
repeat=repeat, repeat=repeat,

View File

@@ -1,4 +1,4 @@
[flake8] [flake8]
ignore = F405, F403, E722, E226, W504, F401, W605 ignore = F405, F403, E722, E226, W504, F401, W605
max-line-length = 120 max-line-length = 120
exclude = .git, rowers/migrations, rowers/tests exclude = .git, rowers/migrations, rowers/tests, rowers/admin.py