Private
Public Access
1
0

passes checks in python3

This commit is contained in:
Sander Roosendaal
2019-02-24 15:57:26 +01:00
parent c7ec31344b
commit 866566172c
51 changed files with 4037 additions and 3999 deletions

View File

@@ -1,3 +1,4 @@
from __future__ import unicode_literals, absolute_import
# All the functionality to connect to SportTracks
from rowers.imports import *
@@ -9,7 +10,7 @@ from rowsandall_app.settings import (
SPORTTRACKS_REDIRECT_URI
)
import mytypes
import rowers.mytypes as mytypes
oauth_data = {
'client_id': SPORTTRACKS_CLIENT_ID,
@@ -64,19 +65,19 @@ def rower_sporttracks_token_refresh(user):
def get_sporttracks_workout_list(user):
r = Rower.objects.get(user=user)
if (r.sporttrackstoken == '') or (r.sporttrackstoken is None):
s = "Token doesn't exist. Need to authorize"
return custom_exception_handler(401,s)
s = "Token doesn't exist. Need to authorize"
return custom_exception_handler(401,s)
elif (timezone.now()>r.sporttrackstokenexpirydate):
s = "Token expired. Needs to refresh."
return custom_exception_handler(401,s)
s = "Token expired. Needs to refresh."
return custom_exception_handler(401,s)
else:
# ready to fetch. Hurray
authorizationstring = str('Bearer ' + r.sporttrackstoken)
headers = {'Authorization': authorizationstring,
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json'}
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities"
s = requests.get(url,headers=headers)
# ready to fetch. Hurray
authorizationstring = str('Bearer ' + r.sporttrackstoken)
headers = {'Authorization': authorizationstring,
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json'}
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities"
s = requests.get(url,headers=headers)
return s
@@ -84,19 +85,19 @@ def get_sporttracks_workout_list(user):
def get_workout(user,sporttracksid):
r = Rower.objects.get(user=user)
if (r.sporttrackstoken == '') or (r.sporttrackstoken is None):
return custom_exception_handler(401,s)
s = "Token doesn't exist. Need to authorize"
return custom_exception_handler(401,s)
s = "Token doesn't exist. Need to authorize"
elif (timezone.now()>r.sporttrackstokenexpirydate):
s = "Token expired. Needs to refresh."
return custom_exception_handler(401,s)
s = "Token expired. Needs to refresh."
return custom_exception_handler(401,s)
else:
# ready to fetch. Hurray
authorizationstring = str('Bearer ' + r.sporttrackstoken)
headers = {'Authorization': authorizationstring,
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json'}
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities/"+str(sporttracksid)
s = requests.get(url,headers=headers)
# ready to fetch. Hurray
authorizationstring = str('Bearer ' + r.sporttrackstoken)
headers = {'Authorization': authorizationstring,
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json'}
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities/"+str(sporttracksid)
s = requests.get(url,headers=headers)
data = s.json()
@@ -139,19 +140,19 @@ def createsporttracksworkoutdata(w):
haslatlon=1
try:
lat = row.df[' latitude'].values
lon = row.df[' longitude'].values
lat = row.df[' latitude'].values
lon = row.df[' longitude'].values
if not lat.std() and not lon.std():
haslatlon = 0
except KeyError:
haslatlon = 0
haslatlon = 0
haspower = 1
try:
power = row.df[' Power (watts)'].astype(int).values
power = row.df[' Power (watts)'].astype(int).values
except KeyError:
haspower = 0
haspower = 0
locdata = []
hrdata = []
@@ -160,18 +161,18 @@ def createsporttracksworkoutdata(w):
powerdata = []
for i in range(len(t)):
hrdata.append(t[i])
hrdata.append(hr[i])
distancedata.append(t[i])
distancedata.append(d[i])
spmdata.append(t[i])
spmdata.append(spm[i])
if haslatlon:
locdata.append(t[i])
locdata.append([lat[i],lon[i]])
if haspower:
powerdata.append(t[i])
powerdata.append(power[i])
hrdata.append(t[i])
hrdata.append(hr[i])
distancedata.append(t[i])
distancedata.append(d[i])
spmdata.append(t[i])
spmdata.append(spm[i])
if haslatlon:
locdata.append(t[i])
locdata.append([lat[i],lon[i]])
if haspower:
powerdata.append(t[i])
powerdata.append(power[i])
try:
@@ -183,37 +184,37 @@ def createsporttracksworkoutdata(w):
st = st.replace(microsecond=0)
if haslatlon:
data = {
"type": "Rowing",
"name": w.name,
"start_time": st.isoformat(),
"total_distance": int(w.distance),
"duration": duration,
"notes": w.notes,
"avg_heartrate": averagehr,
"max_heartrate": maxhr,
"location": locdata,
"distance": distancedata,
"cadence": spmdata,
"heartrate": hrdata,
}
data = {
"type": "Rowing",
"name": w.name,
"start_time": st.isoformat(),
"total_distance": int(w.distance),
"duration": duration,
"notes": w.notes,
"avg_heartrate": averagehr,
"max_heartrate": maxhr,
"location": locdata,
"distance": distancedata,
"cadence": spmdata,
"heartrate": hrdata,
}
else:
data = {
"type": "Rowing",
"name": w.name,
"start_time": st.isoformat(),
"total_distance": int(w.distance),
"duration": duration,
"notes": w.notes,
"avg_heartrate": averagehr,
"max_heartrate": maxhr,
"distance": distancedata,
"cadence": spmdata,
"heartrate": hrdata,
}
data = {
"type": "Rowing",
"name": w.name,
"start_time": st.isoformat(),
"total_distance": int(w.distance),
"duration": duration,
"notes": w.notes,
"avg_heartrate": averagehr,
"max_heartrate": maxhr,
"distance": distancedata,
"cadence": spmdata,
"heartrate": hrdata,
}
if haspower:
data['power'] = powerdata
data['power'] = powerdata
return data
@@ -239,41 +240,41 @@ def workout_sporttracks_upload(user,w):
thetoken = sporttracks_open(user)
if (checkworkoutuser(user,w)):
data = createsporttracksworkoutdata(w)
data = createsporttracksworkoutdata(w)
if not data:
message = "Data error"
stid = 0
return message,stid
authorizationstring = str('Bearer ' + thetoken)
headers = {'Authorization': authorizationstring,
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json'}
authorizationstring = str('Bearer ' + thetoken)
headers = {'Authorization': authorizationstring,
'user-agent': 'sanderroosendaal',
'Content-Type': 'application/json'}
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities.json"
response = requests.post(url,headers=headers,data=json.dumps(data))
url = "https://api.sporttracks.mobi/api/v2/fitnessActivities.json"
response = requests.post(url,headers=headers,data=json.dumps(data))
# check for duplicate error first
if (response.status_code == 409 ):
message = "Duplicate error"
w.uploadedtosporttracks = -1
# check for duplicate error first
if (response.status_code == 409 ):
message = "Duplicate error"
w.uploadedtosporttracks = -1
stid = -1
w.save()
w.save()
return message, stid
elif (response.status_code == 201 or response.status_code==200):
s= response.json()
stid = getidfromresponse(response)
w.uploadedtosporttracks = stid
w.save()
elif (response.status_code == 201 or response.status_code==200):
s= response.json()
stid = getidfromresponse(response)
w.uploadedtosporttracks = stid
w.save()
return 'Successfully synced to SportTracks',stid
else:
s = response
message = "Something went wrong in workout_sporttracks_upload_view: %s" % s.reason
else:
s = response
message = "Something went wrong in workout_sporttracks_upload_view: %s" % s.reason
stid = 0
return message,stid
else:
message = "You are not authorized to upload this workout"
message = "You are not authorized to upload this workout"
stid = 0
return message,stid
@@ -289,33 +290,33 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks',
workouttype = 'other'
if workouttype not in [x[0] for x in Workout.workouttypes]:
workouttype = 'other'
workouttype = 'other'
try:
comments = data['comments']
comments = data['comments']
except:
comments = ''
comments = ''
r = Rower.objects.get(user=user)
try:
rowdatetime = iso8601.parse_date(data['start_time'])
rowdatetime = iso8601.parse_date(data['start_time'])
except iso8601.ParseError:
try:
rowdatetime = datetime.datetime.strptime(data['start_time'],"%Y-%m-%d %H:%M:%S")
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
except:
try:
rowdatetime = dateutil.parser.parse(data['start_time'])
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
except:
rowdatetime = datetime.datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
try:
rowdatetime = datetime.datetime.strptime(data['start_time'],"%Y-%m-%d %H:%M:%S")
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
except:
try:
rowdatetime = dateutil.parser.parse(data['start_time'])
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
except:
rowdatetime = datetime.datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S")
rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc)
starttimeunix = arrow.get(rowdatetime).timestamp
try:
title = data['name']
title = data['name']
except:
title = "Imported data"
title = "Imported data"
try:
res = splitstdata(data['distance'])
@@ -331,41 +332,41 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks',
try:
l = data['location']
l = data['location']
res = splitstdata(l)
times_location = res[0]
latlong = res[1]
latcoord = []
loncoord = []
res = splitstdata(l)
times_location = res[0]
latlong = res[1]
latcoord = []
loncoord = []
for coord in latlong:
lat = coord[0]
lon = coord[1]
latcoord.append(lat)
loncoord.append(lon)
for coord in latlong:
lat = coord[0]
lon = coord[1]
latcoord.append(lat)
loncoord.append(lon)
except:
times_location = times_distance
latcoord = np.zeros(len(times_distance))
loncoord = np.zeros(len(times_distance))
times_location = times_distance
latcoord = np.zeros(len(times_distance))
loncoord = np.zeros(len(times_distance))
if workouttype in mytypes.otwtypes:
workouttype = 'rower'
try:
res = splitstdata(data['cadence'])
times_spm = res[0]
spm = res[1]
res = splitstdata(data['cadence'])
times_spm = res[0]
spm = res[1]
except KeyError:
times_spm = times_distance
spm = 0*times_distance
times_spm = times_distance
spm = 0*times_distance
try:
res = splitstdata(data['heartrate'])
hr = res[1]
times_hr = res[0]
res = splitstdata(data['heartrate'])
hr = res[1]
times_hr = res[0]
except KeyError:
times_hr = times_distance
hr = 0*times_distance
times_hr = times_distance
hr = 0*times_distance
# create data series and remove duplicates
@@ -383,12 +384,12 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks',
# Create dicts and big dataframe
d = {
' Horizontal (meters)': distseries,
' latitude': latseries,
' longitude': lonseries,
' Cadence (stokes/min)': spmseries,
' HRCur (bpm)' : hrseries,
}
' Horizontal (meters)': distseries,
' latitude': latseries,
' longitude': lonseries,
' Cadence (stokes/min)': spmseries,
' HRCur (bpm)' : hrseries,
}
@@ -432,7 +433,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks',
df = df.fillna(0)
df.sort_values(by='TimeStamp (sec)',ascending=True)
timestr = strftime("%Y%m%d-%H%M%S")
# csvfilename ='media/Import_'+str(importid)+'.csv'