oauth working again (CORS allow all)
This commit is contained in:
279
rowers/#ownapistuff.py#
Normal file
279
rowers/#ownapistuff.py#
Normal file
@@ -0,0 +1,279 @@
|
||||
# Python
|
||||
import oauth2 as oauth
|
||||
import cgi
|
||||
import requests
|
||||
import requests.auth
|
||||
import json
|
||||
from django.utils import timezone
|
||||
from datetime import datetime
|
||||
import numpy as np
|
||||
from dateutil import parser
|
||||
import time
|
||||
import math
|
||||
from math import sin,cos,atan2,sqrt
|
||||
|
||||
import urllib
|
||||
import c2stuff
|
||||
|
||||
# Django
|
||||
from django.shortcuts import render_to_response
|
||||
from django.http import HttpResponseRedirect, HttpResponse,JsonResponse
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import authenticate, login, logout
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.decorators import login_required
|
||||
|
||||
# Project
|
||||
# from .models import Profile
|
||||
from rowingdata import rowingdata
|
||||
import pandas as pd
|
||||
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
|
||||
|
||||
TEST_CLIENT_ID = "LTqH0nUe8BySMEJgohJBoo1q4PV16xQJ8uF0XQPU"
|
||||
TEST_CLIENT_SECRET = "HI4bM21rh7pTEXOwCAHLNe3SlLMgbksuzCOARSBbolbQyquZ5quNF8i9PiIaGumbBG4OHCJiQqZJh7Nez6aRiZFgO8POBRVkwCg1fLNk1oY5EJHtLiNrgWY0nbWWDedt"
|
||||
|
||||
TEST_REDIRECT_URI = "http://localhost:8000/rowers/test_callback"
|
||||
|
||||
def custom_exception_handler(exc,message):
|
||||
|
||||
response = {
|
||||
"errors": [
|
||||
{
|
||||
"code": str(exc),
|
||||
"detail": message,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
res = HttpResponse(message)
|
||||
res.status_code = 401
|
||||
res.json = json.dumps(response)
|
||||
|
||||
return res
|
||||
|
||||
def do_refresh_token(refreshtoken):
|
||||
client_auth = requests.auth.HTTPBasicAuth(TEST_CLIENT_ID, TEST_CLIENT_SECRET)
|
||||
post_data = {"grant_type": "refresh_token",
|
||||
"client_secret": TEST_CLIENT_SECRET,
|
||||
"client_id":TEST_CLIENT_ID,
|
||||
"refresh_token": refreshtoken,
|
||||
}
|
||||
headers = {'user-agent': 'sanderroosendaal',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "http://localhost:8000/rowers/o/token"
|
||||
|
||||
response = requests.post(url,
|
||||
data=json.dumps(post_data),
|
||||
headers=headers)
|
||||
|
||||
token_json = response.json()
|
||||
thetoken = token_json['access_token']
|
||||
expires_in = token_json['expires_in']
|
||||
try:
|
||||
refresh_token = token_json['refresh_token']
|
||||
except KeyError:
|
||||
refresh_token = refreshtoken
|
||||
|
||||
return [thetoken,expires_in,refresh_token]
|
||||
|
||||
|
||||
def get_token(code):
|
||||
client_auth = requests.auth.HTTPBasicAuth(TEST_CLIENT_ID, TEST_CLIENT_SECRET)
|
||||
post_data = {"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": TEST_REDIRECT_URI,
|
||||
"client_secret": TEST_CLIENT_SECRET,
|
||||
"client_id":TEST_CLIENT_ID,
|
||||
}
|
||||
headers = {'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "http://localhost:8000/rowers/o/token/"
|
||||
|
||||
|
||||
response = requests.post(url,
|
||||
data=json.dumps(post_data),
|
||||
headers=headers)
|
||||
print response
|
||||
token_json = response.json()
|
||||
thetoken = token_json['access_token']
|
||||
expires_in = token_json['expires_in']
|
||||
refresh_token = token_json['refresh_token']
|
||||
|
||||
return [thetoken,expires_in,refresh_token]
|
||||
|
||||
def make_authorization_url(request):
|
||||
# Generate a random string for the state parameter
|
||||
# Save it for use later to prevent xsrf attacks
|
||||
from uuid import uuid4
|
||||
state = str(uuid4())
|
||||
|
||||
params = {"client_id": TEST_CLIENT_ID,
|
||||
"response_type": "code",
|
||||
"redirect_uri": TEST_REDIRECT_URI,
|
||||
"scope":"write",
|
||||
"state":state}
|
||||
|
||||
|
||||
import urllib
|
||||
url = "http://localhost:8000/rowers/o/authorize" +urllib.urlencode(params)
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
|
||||
def rower_ownapi_token_refresh(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
res = do_refresh_token(r.ownapirefreshtoken)
|
||||
access_token = res[0]
|
||||
expires_in = res[1]
|
||||
refresh_token = res[2]
|
||||
expirydatetime = timezone.now()+timedelta(seconds=expires_in)
|
||||
|
||||
r = Rower.objects.get(user=user)
|
||||
r.ownapitoken = access_token
|
||||
r.tokenexpirydate = expirydatetime
|
||||
r.ownapirefreshtoken = refresh_token
|
||||
|
||||
r.save()
|
||||
return r.ownapitoken
|
||||
|
||||
def get_ownapi_workout_list(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.ownapitoken == '') or (r.ownapitoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (timezone.now()>r.ownapitokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.ownapitoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ownapi.mobi/api/v2/fitnessActivities"
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
|
||||
def get_ownapi_workout(user,ownapiid):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.ownapitoken == '') or (r.ownapitoken is None):
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
elif (timezone.now()>r.ownapitokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.ownapitoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ownapi.mobi/api/v2/fitnessActivities/"+str(ownapiid)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
def createownapiworkoutdata(w):
|
||||
filename = w.csvfilename
|
||||
row = rowingdata(filename)
|
||||
averagehr = int(row.df[' HRCur (bpm)'].mean())
|
||||
maxhr = int(row.df[' HRCur (bpm)'].max())
|
||||
|
||||
# adding diff, trying to see if this is valid
|
||||
t = row.df.ix[:,'TimeStamp (sec)'].values-10*row.df.ix[0,'TimeStamp (sec)']
|
||||
t[0] = t[1]
|
||||
d = row.df.ix[:,'cum_dist'].values
|
||||
d[0] = d[1]
|
||||
t = t.astype(int)
|
||||
d = d.astype(int)
|
||||
spm = row.df[' Cadence (stokes/min)'].astype(int)
|
||||
spm[0] = spm[1]
|
||||
hr = row.df[' HRCur (bpm)'].astype(int)
|
||||
|
||||
haslatlon=1
|
||||
|
||||
try:
|
||||
lat = row.df[' latitude'].values
|
||||
lon = row.df[' longitude'].values
|
||||
except KeyError:
|
||||
haslatlon = 0
|
||||
|
||||
haspower = 1
|
||||
try:
|
||||
power = row.df[' Power (watts)'].values
|
||||
except KeyError:
|
||||
haspower = 0
|
||||
|
||||
locdata = []
|
||||
hrdata = []
|
||||
spmdata = []
|
||||
distancedata = []
|
||||
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])
|
||||
|
||||
|
||||
if haslatlon:
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"name": w.name,
|
||||
# "start_time": str(w.date)+"T"+str(w.starttime)+"Z",
|
||||
"start_time": w.startdatetime.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": int(max(t)),
|
||||
"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": str(w.date)+"T"+str(w.starttime)+"Z",
|
||||
"start_time": w.startdatetime.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": int(max(t)),
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
|
||||
if haspower:
|
||||
data['power'] = powerdata
|
||||
|
||||
return data
|
||||
|
||||
def getidfromresponse(response):
|
||||
t = json.loads(response.text)
|
||||
uri = t['uris'][0]
|
||||
id = uri[len(uri)-13:len(uri)-5]
|
||||
|
||||
return int(id)
|
||||
|
||||
|
||||
1
rowers/.#ownapistuff.py
Normal file
1
rowers/.#ownapistuff.py
Normal file
@@ -0,0 +1 @@
|
||||
E408191@CZ27LT9RCGN72.5176:1479844733
|
||||
@@ -84,6 +84,16 @@ def rdata(file,rower=rrower()):
|
||||
|
||||
return res
|
||||
|
||||
def delete_strokedata(id):
|
||||
query = sa.text('DELETE FROM strokedata WHERE workoutid={id};'.format(
|
||||
id=id,
|
||||
))
|
||||
with engine.connect() as conn, conn.begin():
|
||||
try:
|
||||
result = conn.execute(query)
|
||||
except:
|
||||
print "Database Locked"
|
||||
|
||||
def testdata(time,distance,pace,spm):
|
||||
t1 = np.issubdtype(time,np.number)
|
||||
t2 = np.issubdtype(distance,np.number)
|
||||
|
||||
279
rowers/ownapistuff.py
Normal file
279
rowers/ownapistuff.py
Normal file
@@ -0,0 +1,279 @@
|
||||
# Python
|
||||
import oauth2 as oauth
|
||||
import cgi
|
||||
import requests
|
||||
import requests.auth
|
||||
import json
|
||||
from django.utils import timezone
|
||||
from datetime import datetime
|
||||
import numpy as np
|
||||
from dateutil import parser
|
||||
import time
|
||||
import math
|
||||
from math import sin,cos,atan2,sqrt
|
||||
|
||||
import urllib
|
||||
import c2stuff
|
||||
|
||||
# Django
|
||||
from django.shortcuts import render_to_response
|
||||
from django.http import HttpResponseRedirect, HttpResponse,JsonResponse
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import authenticate, login, logout
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.decorators import login_required
|
||||
|
||||
# Project
|
||||
# from .models import Profile
|
||||
from rowingdata import rowingdata
|
||||
import pandas as pd
|
||||
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
|
||||
|
||||
TEST_CLIENT_ID = "LTqH0nUe8BySMEJgohJBoo1q4PV16xQJ8uF0XQPU"
|
||||
TEST_CLIENT_SECRET = "HI4bM21rh7pTEXOwCAHLNe3SlLMgbksuzCOARSBbolbQyquZ5quNF8i9PiIaGumbBG4OHCJiQqZJh7Nez6aRiZFgO8POBRVkwCg1fLNk1oY5EJHtLiNrgWY0nbWWDedt"
|
||||
|
||||
TEST_REDIRECT_URI = "http://localhost:8000/rowers/test_callback"
|
||||
|
||||
def custom_exception_handler(exc,message):
|
||||
|
||||
response = {
|
||||
"errors": [
|
||||
{
|
||||
"code": str(exc),
|
||||
"detail": message,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
res = HttpResponse(message)
|
||||
res.status_code = 401
|
||||
res.json = json.dumps(response)
|
||||
|
||||
return res
|
||||
|
||||
def do_refresh_token(refreshtoken):
|
||||
client_auth = requests.auth.HTTPBasicAuth(TEST_CLIENT_ID, TEST_CLIENT_SECRET)
|
||||
post_data = {"grant_type": "refresh_token",
|
||||
"client_secret": TEST_CLIENT_SECRET,
|
||||
"client_id":TEST_CLIENT_ID,
|
||||
"refresh_token": refreshtoken,
|
||||
}
|
||||
headers = {'user-agent': 'sanderroosendaal',
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "http://localhost:8000/rowers/o/token"
|
||||
|
||||
response = requests.post(url,
|
||||
data=json.dumps(post_data),
|
||||
headers=headers)
|
||||
|
||||
token_json = response.json()
|
||||
thetoken = token_json['access_token']
|
||||
expires_in = token_json['expires_in']
|
||||
try:
|
||||
refresh_token = token_json['refresh_token']
|
||||
except KeyError:
|
||||
refresh_token = refreshtoken
|
||||
|
||||
return [thetoken,expires_in,refresh_token]
|
||||
|
||||
|
||||
def get_token(code):
|
||||
client_auth = requests.auth.HTTPBasicAuth(TEST_CLIENT_ID, TEST_CLIENT_SECRET)
|
||||
post_data = {"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": TEST_REDIRECT_URI,
|
||||
"client_secret": TEST_CLIENT_SECRET,
|
||||
"client_id":TEST_CLIENT_ID,
|
||||
}
|
||||
headers = {'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'}
|
||||
|
||||
url = "http://localhost:8000/rowers/o/token/"
|
||||
|
||||
|
||||
response = requests.post(url,
|
||||
data=json.dumps(post_data),
|
||||
headers=headers)
|
||||
print response
|
||||
token_json = response.json()
|
||||
thetoken = token_json['access_token']
|
||||
expires_in = token_json['expires_in']
|
||||
refresh_token = token_json['refresh_token']
|
||||
|
||||
return [thetoken,expires_in,refresh_token]
|
||||
|
||||
def make_authorization_url(request):
|
||||
# Generate a random string for the state parameter
|
||||
# Save it for use later to prevent xsrf attacks
|
||||
from uuid import uuid4
|
||||
state = str(uuid4())
|
||||
|
||||
params = {"client_id": TEST_CLIENT_ID,
|
||||
"response_type": "code",
|
||||
"redirect_uri": TEST_REDIRECT_URI,
|
||||
"scope":"write",
|
||||
"state":state}
|
||||
|
||||
|
||||
import urllib
|
||||
url = "http://localhost:8000/rowers/o/authorize" +urllib.urlencode(params)
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
|
||||
def rower_ownapi_token_refresh(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
res = do_refresh_token(r.ownapirefreshtoken)
|
||||
access_token = res[0]
|
||||
expires_in = res[1]
|
||||
refresh_token = res[2]
|
||||
expirydatetime = timezone.now()+timedelta(seconds=expires_in)
|
||||
|
||||
r = Rower.objects.get(user=user)
|
||||
r.ownapitoken = access_token
|
||||
r.tokenexpirydate = expirydatetime
|
||||
r.ownapirefreshtoken = refresh_token
|
||||
|
||||
r.save()
|
||||
return r.ownapitoken
|
||||
|
||||
def get_ownapi_workout_list(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.ownapitoken == '') or (r.ownapitoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (timezone.now()>r.ownapitokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.ownapitoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ownapi.mobi/api/v2/fitnessActivities"
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
|
||||
def get_ownapi_workout(user,ownapiid):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.ownapitoken == '') or (r.ownapitoken is None):
|
||||
return custom_exception_handler(401,s)
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
elif (timezone.now()>r.ownapitokenexpirydate):
|
||||
s = "Token expired. Needs to refresh."
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
# ready to fetch. Hurray
|
||||
authorizationstring = str('Bearer ' + r.ownapitoken)
|
||||
headers = {'Authorization': authorizationstring,
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
url = "https://api.ownapi.mobi/api/v2/fitnessActivities/"+str(ownapiid)
|
||||
s = requests.get(url,headers=headers)
|
||||
|
||||
return s
|
||||
|
||||
def createownapiworkoutdata(w):
|
||||
filename = w.csvfilename
|
||||
row = rowingdata(filename)
|
||||
averagehr = int(row.df[' HRCur (bpm)'].mean())
|
||||
maxhr = int(row.df[' HRCur (bpm)'].max())
|
||||
|
||||
# adding diff, trying to see if this is valid
|
||||
t = row.df.ix[:,'TimeStamp (sec)'].values-10*row.df.ix[0,'TimeStamp (sec)']
|
||||
t[0] = t[1]
|
||||
d = row.df.ix[:,'cum_dist'].values
|
||||
d[0] = d[1]
|
||||
t = t.astype(int)
|
||||
d = d.astype(int)
|
||||
spm = row.df[' Cadence (stokes/min)'].astype(int)
|
||||
spm[0] = spm[1]
|
||||
hr = row.df[' HRCur (bpm)'].astype(int)
|
||||
|
||||
haslatlon=1
|
||||
|
||||
try:
|
||||
lat = row.df[' latitude'].values
|
||||
lon = row.df[' longitude'].values
|
||||
except KeyError:
|
||||
haslatlon = 0
|
||||
|
||||
haspower = 1
|
||||
try:
|
||||
power = row.df[' Power (watts)'].values
|
||||
except KeyError:
|
||||
haspower = 0
|
||||
|
||||
locdata = []
|
||||
hrdata = []
|
||||
spmdata = []
|
||||
distancedata = []
|
||||
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])
|
||||
|
||||
|
||||
if haslatlon:
|
||||
data = {
|
||||
"type": "Rowing",
|
||||
"name": w.name,
|
||||
# "start_time": str(w.date)+"T"+str(w.starttime)+"Z",
|
||||
"start_time": w.startdatetime.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": int(max(t)),
|
||||
"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": str(w.date)+"T"+str(w.starttime)+"Z",
|
||||
"start_time": w.startdatetime.isoformat(),
|
||||
"total_distance": int(w.distance),
|
||||
"duration": int(max(t)),
|
||||
"notes": w.notes,
|
||||
"avg_heartrate": averagehr,
|
||||
"max_heartrate": maxhr,
|
||||
"distance": distancedata,
|
||||
"cadence": spmdata,
|
||||
"heartrate": hrdata,
|
||||
}
|
||||
|
||||
if haspower:
|
||||
data['power'] = powerdata
|
||||
|
||||
return data
|
||||
|
||||
def getidfromresponse(response):
|
||||
t = json.loads(response.text)
|
||||
uri = t['uris'][0]
|
||||
id = uri[len(uri)-13:len(uri)-5]
|
||||
|
||||
return int(id)
|
||||
|
||||
|
||||
@@ -24,6 +24,11 @@ import numpy as np
|
||||
from rowers import urls
|
||||
from rowers.views import error500_view,error404_view,error400_view,error403_view
|
||||
|
||||
from dataprep import delete_strokedata
|
||||
|
||||
|
||||
|
||||
|
||||
class DjangoTestCase(TestCase, MockTestCase):
|
||||
def _pre_setup(self):
|
||||
MockTestCase.setUp(self)
|
||||
@@ -33,12 +38,12 @@ class DjangoTestCase(TestCase, MockTestCase):
|
||||
def _post_teardown(self):
|
||||
TestCase._post_teardown(self)
|
||||
MockTestCase.tearDown(self)
|
||||
delete_strokedata(1)
|
||||
|
||||
# Create your tests here.
|
||||
|
||||
class C2Objects(DjangoTestCase):
|
||||
def test_strokedata(self):
|
||||
print "C2 strokedata"
|
||||
with open('rowers/testdata/c2stroketestdata.txt','r') as infile:
|
||||
res = json.load(infile)
|
||||
|
||||
@@ -60,7 +65,6 @@ class C2Objects(DjangoTestCase):
|
||||
|
||||
class StravaObjects(DjangoTestCase):
|
||||
def test_strokedata(self):
|
||||
print "STRAVA strokedata"
|
||||
timejson = json.load(open('rowers/testdata/stravatimetestdata.txt','r'))
|
||||
velojson = json.load(open('rowers/testdata/stravavelotestdata.txt','r'))
|
||||
distancejson = json.load(open('rowers/testdata/stravadistancetestdata.txt','r'))
|
||||
@@ -136,7 +140,6 @@ class StravaObjects(DjangoTestCase):
|
||||
|
||||
class STObjects(DjangoTestCase):
|
||||
def test_strokedata(self):
|
||||
print "SportTracks strokedata"
|
||||
with open('rowers/testdata/sporttrackstestdata.txt','r') as infile:
|
||||
data = json.load(infile)
|
||||
|
||||
@@ -152,7 +155,6 @@ class STObjects(DjangoTestCase):
|
||||
|
||||
class TestErrorPages(TestCase):
|
||||
def test_error_handlers(self):
|
||||
print "Error Handlers"
|
||||
|
||||
self.assertTrue(urls.handler404.endswith('.error404_view'))
|
||||
self.assertTrue(urls.handler500.endswith('.error500_view'))
|
||||
@@ -178,7 +180,6 @@ class WorkoutTests(TestCase):
|
||||
duration="0:55:00",distance=8000)
|
||||
|
||||
def test_checkworkoutuser(self):
|
||||
print "Check Workout User"
|
||||
u = User.objects.get(username='john')
|
||||
r = Rower.objects.get(user=u)
|
||||
w = Workout.objects.get(user=r)
|
||||
@@ -198,7 +199,6 @@ class C2Tests(TestCase):
|
||||
duration="0:55:00",distance=8000)
|
||||
|
||||
def c2_notokentest(self):
|
||||
print "C2 No token"
|
||||
thetoken = c2_open(self.u)
|
||||
# should raise C2NoTokenError
|
||||
self.assertRaises(C2NoTokenError)
|
||||
@@ -213,7 +213,6 @@ class DataTest(TestCase):
|
||||
|
||||
|
||||
def test_workoutform(self):
|
||||
print "Workout Form"
|
||||
form_data = {
|
||||
'name':'test',
|
||||
'date':'2016-05-01',
|
||||
@@ -227,7 +226,6 @@ class DataTest(TestCase):
|
||||
self.assertTrue(form.is_valid())
|
||||
|
||||
def test_rower_form_withvalidnumbers(self):
|
||||
print "Workout Form with Valid Numbers"
|
||||
form_data = {
|
||||
'max':192,
|
||||
'rest':48,
|
||||
@@ -243,7 +241,6 @@ class DataTest(TestCase):
|
||||
|
||||
|
||||
def test_rower_form_twoequalvalues(self):
|
||||
print "Workout Form Error"
|
||||
form_data = {
|
||||
'max':192,
|
||||
'rest':48,
|
||||
@@ -258,7 +255,6 @@ class DataTest(TestCase):
|
||||
self.assertFalse(form.is_valid())
|
||||
|
||||
def test_rower_form_abovemaxallowed(self):
|
||||
print "Workout Form Error 2"
|
||||
form_data = {
|
||||
'max':300,
|
||||
'rest':48,
|
||||
@@ -273,7 +269,6 @@ class DataTest(TestCase):
|
||||
self.assertFalse(form.is_valid())
|
||||
|
||||
def test_rower_form_wrongorder(self):
|
||||
print "Workout form error 3"
|
||||
form_data = {
|
||||
'max':192,
|
||||
'rest':48,
|
||||
@@ -288,7 +283,6 @@ class DataTest(TestCase):
|
||||
self.assertFalse(form.is_valid())
|
||||
|
||||
def test_rower_form_belowminalloed(self):
|
||||
print "Workout form error 4"
|
||||
form_data = {
|
||||
'max':192,
|
||||
'rest':2,
|
||||
@@ -303,7 +297,6 @@ class DataTest(TestCase):
|
||||
self.assertFalse(form.is_valid())
|
||||
|
||||
def test_rower_form_wrongorder2(self):
|
||||
print "Workout form error 5"
|
||||
form_data = {
|
||||
'max':192,
|
||||
'rest':48,
|
||||
@@ -318,7 +311,6 @@ class DataTest(TestCase):
|
||||
self.assertFalse(form.is_valid())
|
||||
|
||||
def test_painsled(self):
|
||||
print "Test Painsled"
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\testdata.csv'
|
||||
f = open(filename,'rb')
|
||||
file_data = {'file': SimpleUploadedFile(f.name, f.read())}
|
||||
@@ -399,7 +391,6 @@ class ViewTest(TestCase):
|
||||
self.nu = datetime.datetime.now()
|
||||
|
||||
def test_upload_view_notloggedin(self):
|
||||
print "Upload not logged in"
|
||||
response = self.c.post('/rowers/workout/upload/',follow=True)
|
||||
|
||||
|
||||
@@ -409,7 +400,6 @@ class ViewTest(TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_upload_view_sled(self):
|
||||
print "Upload painsled"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\testdata.csv'
|
||||
@@ -452,7 +442,6 @@ class ViewTest(TestCase):
|
||||
|
||||
|
||||
def test_upload_view_notloggedin(self):
|
||||
print "Upload not logged in"
|
||||
response = self.c.post('/rowers/workout/upload/',follow=True)
|
||||
|
||||
|
||||
@@ -462,7 +451,6 @@ class ViewTest(TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_upload_view_sled_negativetime(self):
|
||||
print "Painsled error"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\tim.csv'
|
||||
@@ -504,7 +492,6 @@ class ViewTest(TestCase):
|
||||
|
||||
|
||||
def test_upload_view_sled_noname(self):
|
||||
print "Upload no name"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\testdata.csv'
|
||||
@@ -538,7 +525,6 @@ class ViewTest(TestCase):
|
||||
|
||||
|
||||
def test_upload_view_TCX_CN(self):
|
||||
print "Upload TCX"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\crewnerddata.tcx'
|
||||
@@ -582,7 +568,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_TCX_SpeedCoach2(self):
|
||||
print "Upload TCX 2"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\Speedcoach2example.csv'
|
||||
@@ -613,7 +598,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_TCX_SpeedCoach2(self):
|
||||
print "Upload TCX 3"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\Speedcoach2example.csv'
|
||||
@@ -646,7 +630,6 @@ class ViewTest(TestCase):
|
||||
|
||||
|
||||
def test_upload_view_TCX_SpeedCoach2(self):
|
||||
print "Upload TCX 3"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\speedcoach3test3.csv'
|
||||
@@ -677,7 +660,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_TCX_NoHR(self):
|
||||
print "Upload TCX no HR"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\NoHR.tcx'
|
||||
@@ -708,7 +690,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_TCX_CN(self):
|
||||
print "Upload TCX 10"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\rowinginmotionexample.tcx'
|
||||
@@ -736,7 +717,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_RP(self):
|
||||
print "Upload RowPro"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\RP_testdata.csv'
|
||||
@@ -764,7 +744,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_Mystery(self):
|
||||
print "Upload Mystery"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\mystery.csv'
|
||||
@@ -792,7 +771,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_RP_interval(self):
|
||||
print "Upload RowPro Interval"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\RP_interval.csv'
|
||||
@@ -820,7 +798,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_sled_desktop(self):
|
||||
print "Upload Painsled Desktop"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\painsled_desktop_example.csv'
|
||||
@@ -848,7 +825,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_sled_ergdata(self):
|
||||
print "Upload Ergdata"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\ergdata_example.csv'
|
||||
@@ -876,7 +852,6 @@ class ViewTest(TestCase):
|
||||
os.remove(f_to_be_deleted)
|
||||
|
||||
def test_upload_view_sled_ergstick(self):
|
||||
print "Upload Ergstick"
|
||||
self.c.login(username='john',password='koeinsloot')
|
||||
|
||||
filename = 'C:\\python\\rowingdata\\testdata\\ergstick.csv'
|
||||
@@ -953,7 +928,6 @@ class subroutinetests(TestCase):
|
||||
|
||||
|
||||
def c2stuff(self):
|
||||
print "Test C2 Stuff"
|
||||
data = c2stuff.createc2workoutdata(self.w)
|
||||
jsond = json.dumps(data)
|
||||
data = c2stuff.createc2workoutdata_as_splits(w)
|
||||
@@ -999,7 +973,6 @@ class PlotTests(TestCase):
|
||||
|
||||
|
||||
def test_ote_plots(self):
|
||||
print "Plots"
|
||||
w = self.wote
|
||||
f1 = 'testdata.csv'[:-4]
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
@@ -1107,7 +1080,6 @@ class PlotTests(TestCase):
|
||||
os.remove(fullpathimagename)
|
||||
|
||||
def test_otw_plots(self):
|
||||
print "Plots 2"
|
||||
w = self.wotw
|
||||
f1 = 'testdata.csv'[:-4]
|
||||
timestr = strftime("%Y%m%d-%H%M%S")
|
||||
|
||||
@@ -163,6 +163,8 @@ urlpatterns = [
|
||||
url(r'^workout/(?P<id>\d+)/flexchart$',views.workout_flexchart3_view),
|
||||
url(r'^workout/compare/(?P<id1>\d+)/(?P<id2>\d+)/(?P<xparam>\w+.*)/(?P<yparam>\w+.*)/(?P<plottype>\w+.*)$',views.workout_comparison_view2),
|
||||
url(r'^workout/compare/(?P<id1>\d+)/(?P<id2>\d+)/(?P<xparam>\w+.*)/(?P<yparam>\w+.*)/$',views.workout_comparison_view2),
|
||||
url(r'^test\_callback',views.rower_process_testcallback),
|
||||
|
||||
]
|
||||
|
||||
if settings.DEBUG:
|
||||
|
||||
@@ -29,6 +29,8 @@ from c2stuff import C2NoTokenError
|
||||
from iso8601 import ParseError
|
||||
import stravastuff
|
||||
import sporttracksstuff
|
||||
import ownapistuff
|
||||
from ownapistuff import TEST_CLIENT_ID, TEST_CLIENT_SECRET, TEST_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
|
||||
from rowsandall_app.settings import SPORTTRACKS_CLIENT_ID, SPORTTRACKS_REDIRECT_URI, SPORTTRACKS_CLIENT_SECRET
|
||||
import requests
|
||||
@@ -1169,6 +1171,7 @@ def rower_process_stravacallback(request):
|
||||
return imports_view(request,successmessage=successmessage)
|
||||
|
||||
|
||||
|
||||
@login_required()
|
||||
def rower_process_sporttrackscallback(request):
|
||||
code = request.GET['code']
|
||||
@@ -1190,6 +1193,26 @@ def rower_process_sporttrackscallback(request):
|
||||
successmessage = "Tokens stored. Good to go"
|
||||
return imports_view(request,successmessage=successmessage)
|
||||
|
||||
@login_required()
|
||||
def rower_process_testcallback(request):
|
||||
code = request.GET['code']
|
||||
res = ownapistuff.get_token(code)
|
||||
|
||||
|
||||
access_token = res[0]
|
||||
expires_in = res[1]
|
||||
refresh_token = res[2]
|
||||
expirydatetime = timezone.now()+datetime.timedelta(seconds=expires_in)
|
||||
|
||||
text = "Access Token:\n"
|
||||
text += access_token
|
||||
|
||||
text += "\n\nRefresh Token:\n"
|
||||
text += refresh_token
|
||||
|
||||
return HttpResponse(text)
|
||||
|
||||
|
||||
@login_required()
|
||||
def histo_all(request,theuser=0):
|
||||
promember=0
|
||||
@@ -3731,7 +3754,7 @@ def workout_upload_view(request,message=""):
|
||||
'user-agent': 'sanderroosendaal',
|
||||
'Content-Type': 'application/json'}
|
||||
import urllib
|
||||
url = "https://log.concept2.com/api/users/%s/results" % (c2userid)
|
||||
url = "httpvs://log.concept2.com/api/users/%s/results" % (c2userid)
|
||||
response = requests.post(url,headers=headers,data=json.dumps(data))
|
||||
|
||||
# response = c2stuff.workout_c2_upload(request.user,w)
|
||||
@@ -4556,7 +4579,7 @@ def strokedatajson(request,id):
|
||||
res = df.to_csv(csvfilename,index_label='index')
|
||||
row.csvfilename = csvfilename
|
||||
row.save()
|
||||
|
||||
datadf = dataprep.dataprep(data,id=row.id,bands=True,barchart=True,otwpower=True)
|
||||
except:
|
||||
return HttpResponse("Not OK")
|
||||
# mangling
|
||||
|
||||
Reference in New Issue
Block a user