本文整理汇总了Python中stravalib.Client.exchange_code_for_token方法的典型用法代码示例。如果您正苦于以下问题:Python Client.exchange_code_for_token方法的具体用法?Python Client.exchange_code_for_token怎么用?Python Client.exchange_code_for_token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stravalib.Client
的用法示例。
在下文中一共展示了Client.exchange_code_for_token方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authorization
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def authorization():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
state = request.args.get('state')
if error:
return render_template('authorization_error.html', error=error)
else:
code = request.args.get('code')
client = Client()
access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'],
client_secret=app.config['STRAVA_CLIENT_SECRET'],
code=code)
# Use the now-authenticated client to get the current athlete
strava_athlete = client.get_athlete()
athlete_model = data.register_athlete(strava_athlete, access_token)
multiple_teams = None
no_teams = False
team = None
try:
team = data.register_athlete_team(strava_athlete=strava_athlete, athlete_model=athlete_model)
except bafs.exc.MultipleTeamsError as multx:
multiple_teams = multx.teams
except bafs.exc.NoTeamsError:
no_teams = True
return render_template('authorization_success.html', athlete=strava_athlete,
team=team, multiple_teams=multiple_teams,
no_teams=no_teams)
示例2: do_GET
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def do_GET(self):
request_path = self.path
parsed_path = urlparse.urlparse(request_path)
client = Client()
if request_path.startswith('/authorization'):
self.send_response(200)
self.send_header(six.b("Content-type"), six.b("text/plain"))
self.end_headers()
self.wfile.write(six.b("Authorization Handler\n\n"))
code = urlparse.parse_qs(parsed_path.query).get('code')
if code:
code = code[0]
token_response = client.exchange_code_for_token(client_id=self.server.client_id,
client_secret=self.server.client_secret,
code=code)
access_token = token_response['access_token']
self.server.logger.info("Exchanged code {} for access token {}".format(code, access_token))
self.wfile.write(six.b("Access Token: {}\n".format(access_token)))
else:
self.server.logger.error("No code param received.")
self.wfile.write(six.b("ERROR: No code param recevied.\n"))
else:
url = client.authorization_url(client_id=self.server.client_id,
redirect_uri='http://localhost:{}/authorization'.format(self.server.server_port))
self.send_response(302)
self.send_header(six.b("Content-type"), six.b("text/plain"))
self.send_header(six.b('Location'), six.b(url))
self.end_headers()
self.wfile.write(six.b("Redirect to URL: {}\n".format(url)))
示例3: get_login_token
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def get_login_token():
last_activity = None
# auth_token = ""
if not os.path.exists(STRAVA_ACCESS_TOKEN_STRING_FNAME):
print '* Obtain a request token ...'
strava_client = Client()
# auth_url = strava_client.authorization_url(client_id='601', redirect_uri='http://127.0.0.1:5000/authorisation')
client_secret = open(STRAVA_CLIENT_SECRET_STRING_FNAME).read().strip()
print client_secret
client_code = open(STRAVA_CLIENT_CODE_STRING_NAME).read().strip()
print client_code
auth_token = strava_client.exchange_code_for_token(client_id='601',
client_secret= client_secret,
code = client_code)
print auth_token
f = open(STRAVA_ACCESS_TOKEN_STRING_FNAME, 'w')
f.write(auth_token)
else:
print '* Reading request token from file ...'
f = open(STRAVA_ACCESS_TOKEN_STRING_FNAME)
auth_token = f.read()
f.close()
print auth_token
return auth_token
示例4: authorize
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def authorize(request):
code = request.GET.get('code')
print("Code", code)
print(settings.STATIC_URL)
client = Client()
access_token = client.exchange_code_for_token(client_id=11103,
client_secret=settings.MYSECRETKEY,
code=code)
return HttpResponse('Your access token is {0}'.format(access_token))
示例5: logged_in
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def logged_in():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
state = request.args.get('state')
if error:
return render_template('login_error.html',
error=error,
competition_title=config.COMPETITION_TITLE)
else:
code = request.args.get('code')
client = Client()
token_dict = client.exchange_code_for_token(client_id=config.STRAVA_CLIENT_ID,
client_secret=config.STRAVA_CLIENT_SECRET,
code=code)
# Use the now-authenticated client to get the current athlete
strava_athlete = client.get_athlete()
athlete_model = data.update_athlete_auth(strava_athlete, token_dict)
if not athlete_model:
return render_template('login_error.html',
error="ATHLETE_NOT_FOUND",
competition_title=config.COMPETITION_TITLE)
multiple_teams = None
no_teams = False
team = None
message = None
try:
team = data.register_athlete_team(
strava_athlete=strava_athlete,
athlete_model=athlete_model,
)
except MultipleTeamsError as multx:
multiple_teams = multx.teams
message = multx
except NoTeamsError as noteamsx:
no_teams = True
message = noteamsx
if not no_teams:
auth.login_athlete(strava_athlete)
return redirect(url_for('user.rides'))
else:
return render_template(
'login_results.html',
athlete=strava_athlete,
team=team,
multiple_teams=multiple_teams,
no_teams=no_teams,
message=message,
competition_title=config.COMPETITION_TITLE,
)
示例6: getToken
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def getToken():
access_token = session.get('access_token')
if access_token != None:
return access_token
# the code is in the results thingy!
code = request.args.get('code')
if code == None:
return None
client = Client()
access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID,\
client_secret=MY_STRAVA_CLIENT_SECRET,\
code=code)
session['access_token'] = access_token
return access_token
示例7: authorization
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def authorization():
my_client_id = app.vars['client_id']
my_client_secret = app.vars['client_secret']
code = request.args.get('code')
client = Client()
access_token = client.exchange_code_for_token(client_id = my_client_id, \
client_secret = my_client_secret, code = code)
app.vars['access_token'] = access_token
my_client = StravaClient()
app.vars['athlete'] = my_client.get_athlete()
return redirect('power_profile')
示例8: authorization
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def authorization():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
if error:
return render_template('authorization_error.html',
error=error,
competition_title=config.COMPETITION_TITLE)
else:
code = request.args.get('code')
client = Client()
token_dict = client.exchange_code_for_token(
client_id=config.STRAVA_CLIENT_ID,
client_secret=config.STRAVA_CLIENT_SECRET,
code=code,
)
# Use the now-authenticated client to get the current athlete
strava_athlete = client.get_athlete()
athlete_model = data.register_athlete(strava_athlete, token_dict)
multiple_teams = None
no_teams = False
team = None
message = None
try:
team = data.register_athlete_team(
strava_athlete=strava_athlete,
athlete_model=athlete_model,
)
except MultipleTeamsError as multx:
multiple_teams = multx.teams
message = multx
except NoTeamsError as noteamx:
no_teams = True
message = noteamx
return render_template(
'authorization_success.html',
athlete=strava_athlete,
team=team,
multiple_teams=multiple_teams,
no_teams=no_teams,
message=message,
competition_title=config.COMPETITION_TITLE,
)
示例9: get_activities_from_strava
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def get_activities_from_strava():
last_activity = None
if not os.path.exists(STRAVA_ACCESS_TOKEN_STRING_FNAME):
print '* Obtain a request token ...'
strava_client = Client()
auth_url = strava_client.authorization_url(client_id='601', redirect_uri='http://127.0.0.1:5000/authorisation')
print auth_url
auth_token = strava_client.exchange_code_for_token(client_id='601', client_secret='600580e02b4814c75c93d3a60e15077147895776', code = '74cc257e6bc370d9da44cabc8852f3667ad95515')
print auth_token
# write the access token to file; next time we just read it from file
if DEBUG:
print 'Writing file', STRAVA_ACCESS_TOKEN_STRING_FNAME
fobj = open(STRAVA_ACCESS_TOKEN_STRING_FNAME, 'w')
fobj.write(auth_token)
fobj.close()
else:
if DEBUG:
print 'Reading file', STRAVA_ACCESS_TOKEN_STRING_FNAME
fobj = open(STRAVA_ACCESS_TOKEN_STRING_FNAME)
access_token_string = fobj.read()
print access_token_string
#access_token = oauth.OAuthToken.from_string(access_token_string)
strava_client = Client(access_token=access_token_string)
activities = strava_client.get_activities(limit=10)
# for activity in activities:
# details = strava_client.get_activity(activity_id=activity.id)
# print details.name
# print unithelper.kilometers(details.distance)
# print details.start_date_local
# print details.elapsed_time
# print details.calories
# print details.type
# print "------"
# fobj.close()
for activity in activities:
last_activity = activity
return strava_client.get_activity(activity_id=activity.id)
示例10: authorization
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def authorization(request):
'''
Trades in the `code` sent from Strava for an `access_token`.
Ties that `access_token` to a users session.
'''
code = request.GET.get('code', None)
client = Client()
access_token = client.exchange_code_for_token(
client_id=os.environ.get('STRAVA_CLIENT_ID', None),
client_secret=os.environ.get('STRAVA_CLIENT_SECRET', None),
code=code
)
request.session['access_token'] = access_token
return redirect(index)
示例11: token
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def token(request):
# Get temporary code after the request
code = request.GET.get("code")
# exchange the code for an access token.
client = Client()
access_token = client.exchange_code_for_token(client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET,
code=code)
# Get Athlete
athlete = client.get_athlete()
# See if the athlete exists in our DB
# current_athlete = get_object_or_404(Athlete, id_strava = athlete.id)
# current_athlete = ""
try:
current_athlete = Athlete.objects.get(id_strava = athlete.id)
except (KeyError, Athlete.DoesNotExist):
current_athlete = Athlete(first_name=athlete.firstname, last_name=athlete.lastname, access_token=access_token, id_strava = athlete.id )
current_athlete.save()
# **************************
# Prep content for the HTML page.
# Get Activities.
activities = client.get_activities()
# Make a list of activities to send to the html page. These are all the activities for this athlete.
activity_list = []
name_list = []
for a in activities:
temp = [a.id, a.name, a.distance, a.moving_time, a.elapsed_time, a.start_date_local]
activity_list.append(temp)
# information to send to the html page
context = { 'activity_list': activity_list, 'current_athlete': current_athlete }
template = loader.get_template('shred/activities.html')
return HttpResponse(template.render(context))
示例12: authorize_strava
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def authorize_strava():
if request.args.get('state') and request.args.get('code'):
id = request.args.get('state')
strava_code = request.args.get('code')
strava_client_id = current_app.config['STRAVA_CLIENT_ID']
strava_client_secret = current_app.config['STRAVA_CLIENT_SECRET']
strava_client = Client()
try:
access_token = (
strava_client.exchange_code_for_token(
client_id=strava_client_id,
client_secret=strava_client_secret,
code=strava_code))
except Exception:
return redirect(url_for('racer.index'))
else:
racer = Racer.query.get_or_404(id)
strava_client = Client(access_token)
strava_athlete = strava_client.get_athlete()
existing_racer = Racer.query\
.filter_by(strava_id=strava_athlete.id)\
.first()
if existing_racer:
flash('Racer ' + existing_racer.name +
' already linked with Strava account for ' +
strava_athlete.firstname + ' ' +
strava_athlete.lastname + '!')
current_app.logger.info('%s[%d] failed against %s[%d]',
racer.name, racer.id,
existing_racer.name, existing_racer.id)
return redirect(url_for('racer.details', id=id))
else:
racer.strava_access_token = access_token
racer.strava_id = strava_athlete.id
racer.strava_email = strava_athlete.email
racer.profile_url = strava_athlete.profile
db.session.commit()
current_app.logger.info('%s[%d]', racer.name, racer.id)
flash('Racer ' + racer.name + ' linked with Strava!')
return redirect(url_for('racer.details', id=id))
return redirect(url_for('racer.index'))
示例13: logged_in
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def logged_in():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
state = request.args.get('state')
if error:
return render_template('login_error.html', error=error)
else:
code = request.args.get('code')
client = Client()
access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'],
client_secret=app.config['STRAVA_CLIENT_SECRET'],
code=code)
# Use the now-authenticated client to get the current athlete
strava_athlete = client.get_athlete()
athlete_model = db.session.query(Athlete).get(strava_athlete.id)
if not athlete_model:
return render_template('login_error.html', error="ATHLETE_NOT_FOUND")
multiple_teams = None
no_teams = False
team = None
try:
team = data.register_athlete_team(strava_athlete=strava_athlete, athlete_model=athlete_model)
except bafs.exc.MultipleTeamsError as multx:
multiple_teams = multx.teams
except bafs.exc.NoTeamsError:
no_teams = True
if not no_teams:
auth.login_athlete(strava_athlete)
return redirect(url_for('user.rides'))
else:
return render_template('login_results.html', athlete=strava_athlete,
team=team, multiple_teams=multiple_teams,
no_teams=no_teams)
示例14: logged_in
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def logged_in():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
state = request.args.get('state')
if error:
return render_template('login_error.html', error=error)
else:
code = request.args.get('code')
client = Client()
access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'],
client_secret=app.config['STRAVA_CLIENT_SECRET'],
code=code)
# Probably here you'd want to store this somewhere -- e.g. in a database.
strava_athlete = client.get_athlete()
return render_template('login_results.html', athlete=strava_athlete, access_token=access_token)
示例15: authorization
# 需要导入模块: from stravalib import Client [as 别名]
# 或者: from stravalib.Client import exchange_code_for_token [as 别名]
def authorization(request):
client = Client()
code = request.GET['code']
access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID, client_secret=MY_STRAVA_CLIENT_SECRET, code=code)
# making a global variable to be used across views. don't know how this will work in practice
client = Client(access_token=access_token)
athlete = client.get_athlete() # Get current athlete details
global athleteId
athleteId = athlete.id
# if athlete doesn't exist, add them
if len(Athlete.objects.filter(athleteId=athleteId)) == 0:
ath = Athlete.objects.create(name=str(athlete.firstname+' '+athlete.lastname), athleteId=athleteId, profilePic=athlete.profile, city=athlete.city, country=athlete.country, sex=athlete.sex, premium=athlete.premium, created_at=athlete.created_at, updated_at=athlete.updated_at, followers=athlete.follower_count, friends=athlete.friend_count, email=athlete.email, weight=athlete.weight, meas_pref=athlete.measurement_preference, runsSummary = DataFrame({}).to_json(orient='records'), fitLines = DataFrame({}).to_json(orient='records'), masterList = DataFrame({}).to_json(orient='records'))
ath.profilePic.name = "rudyzPic"
ath.save(update_fields=['profilePic'])
# if athlete already exists, draw their file
elif len(Athlete.objects.filter(athleteId=athleteId)) == 1:
ath = Athlete.objects.get(athleteId=athleteId)
############################################
##### compiling new runs, updating summary
# athlete's existing runs summary
existingSummary = DataFrame(pd.read_json(ath.runsSummary))
existingFitlines = DataFrame(pd.read_json(ath.fitLines))
masterList = DataFrame(pd.read_json(ath.masterList))
activities = list(client.get_activities())
# activity IDs of runs already in the system
try:
ids = existingSummary.activityId
except AttributeError:
ids = []
for i in range(len(activities)):
#for i in range(30,37):
# Ignoring activities already in the system
if (len(ids) == 0) or (float(activities[i].id) not in list(ids)):
try:
# compiling df for raw json-ization
activityId = activities[i].id
run = client.get_activity_streams(activityId, types=['time','latlng','distance','heartrate','altitude','cadence'])
latlng = run['latlng'].data
time = run['time'].data
distance = run['distance'].data
heartrate = run['heartrate'].data
altitude = run['altitude'].data
cadence = run['cadence'].data
date = activities[i].start_date_local
activity = activityId
dfi = thresher.assemble(date, activityId, heartrate, distance, time, altitude, latlng, cadence)
# basic cleanup, only removing totally unreasonable values
dfi = thresher.basicClean(dfi)
# if we ever want to try our hand at improving strava's speed data (ie by predicting speed when GPS blanks), intervene here:
#dfi = thresher.addDistDeltas(dfi)
try:
fitline = thresher.getFitlineLws(dfi) # this adds speed-shifted columns
except:
fitline = pd.DataFrame({})
try:
mafScore = fitline[fitline.hr == 140.0].avgSpeed.iloc[0]
print "MAF "
print mafScore
except:
mafScore = np.nan
fitline_json = fitline.to_json(orient='records')
# getting summary info for run (as one-entry dict)
runSummary = thresher.getSingleSummaryDf(dfi)
# adding mafScore to summary
runSummary['mafScore'] = mafScore
print runSummary
# adding predicted hr and speed values
#dfi = thresher.getPred(dfi)
# saving entry to database
Activity.objects.create(act_id = activityId, name=str(activities[i].name), description=activities[i].description, act_type=activities[i].type, date=activities[i].start_date_local, timezone=activities[i].timezone, df=dfi.to_json(orient='records'), avgHr=runSummary['avgHr'], hrVar=runSummary['variation'], realMiles=runSummary['realMiles'], recovery=runSummary['recovery'], easy=runSummary['easy'], stamina=runSummary['stamina'], impulse=runSummary['impulse'], totalTime=runSummary['totalTime'], totalDist=runSummary['totalDist'], climb=runSummary['climb'], fitline=fitline_json, mafScore=mafScore, athlete=ath)
# updating runs summary
existingSummary = existingSummary.append(runSummary, ignore_index=True)
existingFitlines = existingFitlines.append(fitline, ignore_index=True)
#.........这里部分代码省略.........