本文整理汇总了Python中stravalib.Client类的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
with open('secrets.txt') as f:
MY_STRAVA_CLIENT_ID = f.readline().strip()
MY_STRAVA_CLIENT_SECRET = f.readline().strip()
with open('maps.txt') as f:
gid = f.readline().strip()
session['gid']=gid #google map api key
access_token = getToken(MY_STRAVA_CLIENT_ID, MY_STRAVA_CLIENT_SECRET)
if access_token == None:
return redirectAuth(MY_STRAVA_CLIENT_ID)
#session['access_token'] = access_token
client = Client(access_token=session['access_token'])
athlete = client.get_athlete() # Get current athlete details
clubs = athlete.clubs
session['num_clubs']=len(clubs)
cnames = []
cids = []
for i in range(len(clubs)):
cnames.append(clubs[i].name)
cids.append(clubs[i].id)
session['cids']=cids
session['cnames']=cnames
session['athlete_name'] = athlete.firstname + ' ' + athlete.lastname
return redirect('/cluboptions')
示例2: upload_files
def upload_files(self, files):
"""
Upload files to Strava
"""
# connect to Strava API
client = Client(self.config.strava["access_token"])
for fn in files:
try:
upload = client.upload_activity(open(self.src_path + fn, "r"),
"fit")
activity = upload.wait(30, 10)
# if a file has been uploaded, copy it locally, as this ensures
# we don't attempt to re-upload the same activity in future
if activity:
shutil.copy(self.src_path + fn, self.dest_path + fn)
logging.debug("new file uploaded: {0}, {1} ({2})".format(
activity.name, activity.distance, fn))
except exc.ActivityUploadFailed as error:
print error
示例3: process
def process():
token = session.get('access_token', None)
if token is None:
return redirect(url_for('login'))
client = Client(token)
athlete = client.get_athlete()
activities = client.get_activities()
points = [pnt for a in activities for pnt in (a.end_latlng, a.start_latlng) if pnt]
#temp = [pnt for ints in point_intercepts(points) for pnt in ints]
#temp = filter_close_points(points)
seg = []
for grps in group_points(points):
out = []
for pnt in grps:
out.append("<trkpt lat=\"{0.lat}\" lon=\"{0.lon}\"></trkpt>".format(pnt))
seg.append("<trkseg>{}</trkseg>".format("".join(out)))
return """<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.0">
<name>TEST</name>
<trk>{}</trk>
</gpx>""".format("".join(seg))
return "<html><body><img src='{}'/>{} {}</body></html>".format(athlete.profile, athlete.firstname, athlete.lastname)
示例4: authorization
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)
示例5: do_GET
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)))
示例6: get_login_token
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
示例7: main
def main():
access_token = getToken()
if access_token == None:
return redirectAuth()
client = Client(access_token=access_token)
athlete = client.get_athlete() # Get current athlete details
#if you want a simple output of first name, last name, just use this line:
#return athlete.firstname + ' ' + athlete.lastname
#now get most recent activity for this athlete...
names = []
maps = []
for a in client.get_activities(before = "2016-08-12T00:00:00Z", limit=1):
names.append(a.name)
maps.append(a.map)
# another simple output for this bit is to return the name of the route
#return names[0]
# but a sightly more complicated output is this matplotlib figure --
m = maps[0]
summary_lat_lon = polyline.decode(m.summary_polyline)
lats = [i[0] for i in summary_lat_lon]
lons = [i[1] for i in summary_lat_lon]
session['name']=names[0]
session['lats']=lats
session['lons']=lons
return redirect('/simple.png')
示例8: authorize
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))
示例9: logged_in
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,
)
示例10: join
def join():
c = Client()
public_url = c.authorization_url(client_id=app.config['STRAVA_CLIENT_ID'],
redirect_uri=url_for('.authorization', _external=True),
approval_prompt='auto')
private_url = c.authorization_url(client_id=app.config['STRAVA_CLIENT_ID'],
redirect_uri=url_for('.authorization', _external=True),
approval_prompt='auto',
scope='view_private')
return render_template('authorize.html', public_authorize_url=public_url, private_authorize_url=private_url)
示例11: login
def login():
c = Client()
url = c.authorization_url(
client_id=config.STRAVA_CLIENT_ID,
redirect_uri=url_for('.logged_in', _external=True),
approval_prompt='auto',
scope=['read_all', 'activity:read_all', 'profile:read_all'],
)
return render_template('login.html',
authorize_url=url,
competition_title=config.COMPETITION_TITLE)
示例12: process
def process():
token = session.get('access_token', None)
if token is None:
return redirect(url_for('login'))
client = Client(token)
athlete = client.get_athlete()
activities = client.get_activities()
for a in activities:
if not a.commute and "commute" in a.name.lower():
print(a)
client.update_activity(a.id, commute=True)
return "<html><body>processed</body></html>"
示例13: strava_email
def strava_email(self):
if self.strava_access_token is None:
return None
if self.strava_profile_last_fetch is None or\
(datetime.now(pytz.timezone('UTC')) -\
self.strava_profile_last_fetch)\
> timedelta(minutes=5):
self.strava_profile_last_fetch = datetime.now(pytz.timezone('UTC'))
strava_client = Client(self.strava_access_token)
strava_athlete = strava_client.get_athlete()
self.strava_email = strava_athlete.email
return self._strava_email
示例14: get_activity_map
def get_activity_map():
# just to see if i can plot my own activity map!
f = open('secrets.txt', 'r')
MY_STRAVA_CLIENT_ID = f.readline().strip()
MY_STRAVA_CLIENT_SECRET = f.readline().strip()
STORED_ACCESS_TOKEN = f.readline().strip()
f.close()
from stravalib import Client
client = Client(access_token=STORED_ACCESS_TOKEN)
client.get_athlete(7656735) # Get current athlete details
#now get most recent activity for this athlete...
a=client.get_activities(before = "2016-08-11T00:00:00Z", limit=1)
session['map']=a.map
session['name']=a.name
示例15: getToken
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