本文整理汇总了Python中stravalib.client.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
的用法示例。
在下文中一共展示了Client.exchange_code_for_token方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def get(request):
""" Request -and store- a strava access token. """
client = Client()
# Extract the code from the response
code = request.GET.get('code')
access_token = client.exchange_code_for_token(
client_id=settings.STRAVA_CLIENT_ID,
client_secret=settings.STRAVA_CLIENT_SECRET,
code=code
)
strava_athlete = client.get_athlete()
try:
athlete = Athlete.objects.get(strava_id=strava_athlete.id)
athlete.strava_token = access_token
except Athlete.DoesNotExist:
athlete = Athlete(strava_id=strava_athlete.id, strava_token=access_token)
athlete.save()
cache_key = _get_cache_key(request)
cache.delete(cache_key)
redir_url = '{}?start_date={}&end_date={}'.format(
reverse_lazy('strava-summary'),
_get_start_date(request),
_get_end_date(request)
)
return HttpResponseRedirect(redir_url)
示例2: get
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def get(self):
code = self.request.get('code')
client = Client()
access_token = client.exchange_code_for_token(client_id=conf.SV_CLIENT_ID, client_secret=conf.SV_CLIENT_SECRET, code=code)
user_id = UserManager().AddUserToken(access_token)
self.redirect('/user/{0}'.format(user_id))
示例3: oauth_authorized
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def oauth_authorized():
client = Client()
code = request.args.get('code')
access_token = client.exchange_code_for_token(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
code=code)
session['access_token'] = access_token
return redirect(url_for('index'))
示例4: authorization
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def authorization():
code = request.args.get('code')
client = Client()
access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID,
client_secret=MY_STRAVA_CLIENT_SECRET,
code=code)
response = redirect("/")
response.set_cookie('access_token', access_token)
return response
示例5: auth
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def auth():
try:
code = request.args["code"]
c = Client()
token = c.exchange_code_for_token(app.config['STRAVA_ID'], app.config['STRAVA_SECRET'], code)
except (KeyError, requests.exceptions.HTTPError):
return redirect("/")
session["token"] = c.access_token = token
a = c.get_athlete() # Technically shouldn't be needed as the athlete details are returned in the oauth call
session["athlete"] = {"firstname": a.firstname, "picture": a.profile_medium}
return redirect("/")
示例6: set_access_token
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def set_access_token(request):
""" Exchange the provided code for an access token and store it
"""
# Our strava code
json = request.json_body
code = json['code']
# If we don't have a strava secret, we can't make the key exchange
if 'strava' not in request.registry.settings['secrets']:
request.response.status_int = 500
return
# Exchange the code for an access token
# The API will throw an unspecified error if code is invalid.
# Catch that rather than taking down the server.
access_token = ""
try:
client = StravaClient()
access_token = client.exchange_code_for_token(client_id=request.registry.settings['secrets']['strava']['strava_id'],
client_secret=request.registry.settings['secrets']['strava']['strava_secret'],
code=code)
except:
# Return an error
request.response.status_int = 502
return
# Our admin object
admin = _get_admin(request)
#Create the access token if it doesn't exist, or update the stored one
if not admin.exists_document('strava_access_token'):
# Store the access token
admin.create_document({'strava_access_token': access_token}, doc_id='strava_access_token')
else:
# Update the stored access token
stored_access_token = admin.get_document('strava_access_token')
try:
admin.update_document({'strava_access_token': access_token, '_id':'strava_access_token', '_rev':stored_access_token['_rev']})
except:
# We likely hit a race condition where the _rev is no longer valid. Return accordingly.
request.response.status_int = 409
return
# Return appropriately
request.response.status_int = 200
return {
'access_token':
access_token
}
示例7: authorized
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def authorized():
# get access token to make requests
client = Client()
code = request.args.get('code')
client.access_token = client.exchange_code_for_token(client_id=creds.client_id, client_secret=creds.client_secret, code=code) # add id and secret
# get data
today = datetime.datetime.strptime(str(datetime.date.today()), "%Y-%m-%d")
one_month_ago = today - dateutil.relativedelta.relativedelta(months=1)
athlete = client.get_athlete()
activities = client.get_activities(after=one_month_ago)
rides = toolkit.get_activity_types(activities, 'ride')
runs = toolkit.get_activity_types(activities, 'run')
ride_set = ActivitySet("Rides", rides)
run_set = ActivitySet("Runs", runs)
return render_template('main.html', athlete=athlete, activity_sets=[ride_set, run_set])
示例8: auth_success
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def auth_success(request):
temp_code = request.GET.get('code') # temp auth code
print(temp_code)
client = Client()
token = client.exchange_code_for_token(5928, 'a486a0b19c8d16aef41090371b7726dc510ee4a7', temp_code)
if not athlete.objects.filter(pk=client.get_athlete().id):
new_athlete = athlete(
id = client.get_athlete().id,
firstname = client.get_athlete().firstname,
lastname = client.get_athlete().lastname,
access_token = token
)
new_athlete.save()
data_scraper(after_utc, before_utc, client.get_athlete().id)
result = 'added'
else:
result = 'already exists'
return render(request, 'auth_success.html', {'leaderboard':get_leaderboard(), 'result':result})
示例9: token_exchange
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def token_exchange(self, request):
if 'code' in request.data:
try:
strava_client = Client()
response = strava_client.exchange_code_for_token(SOCIAL_AUTH_STRAVA_KEY, SOCIAL_AUTH_STRAVA_SECRET, request.data['code'])
leet = Athlete.objects.get(pk=request.user.pk)
leet.strava_api_token = response
leet.save()
except HTTPError as e:
code = e.args[0][:3]
message = e.args[0][3:]
return Response({
'status': code,
'message': message
}, status=int(code))
else:
return Response({
'status': 'Bad Request',
'message': '"code" is required'
}, status=status.HTTP_400_BAD_REQUEST)
return Response({}, status.HTTP_201_CREATED)
示例10: auth
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
def auth():
try:
code = request.args["code"]
c = Client()
token = c.exchange_code_for_token(app.config['STRAVA_ID'], app.config['STRAVA_SECRET'], code)
except (KeyError, requests.exceptions.HTTPError):
return redirect("/")
session["token"] = c.access_token = token
a = c.get_athlete() # Technically shouldn't be needed as the athlete details are returned in the oauth call
session["athlete"] = {"name": a.firstname, "picture": a.profile_medium, "id": a.id}
# lookup athlete in db
cur = g.db.execute('select * from users where id = {}'.format(a.id))
x = cur.fetchall()
print x
if not x:
# Create the object in the db
cur = g.db.cursor()
cur.execute('insert into users (id, name, picture) values (?, ?, ?)', (a.id, a.firstname, a.profile))
g.db.commit()
cur.close()
return redirect("/")
示例11: int
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
client_id = cfg.get("StravaClient", "ClientId")
client_secret = cfg.get("StravaClient", "ClientSecret")
port = int(cfg.get("Application", "Port"))
# setup webserver for authentication redirect
httpd = http.server.HTTPServer(('127.0.0.1', port), AuthHandler)
# The url to authorize from
authorize_url = client.authorization_url(client_id=client_id, redirect_uri='http://localhost:{port}/authorized'.format(port=port), scope='view_private,write')
# Open the url in your browser
webbrowser.open(authorize_url, new=0, autoraise=True)
# wait until you click the authorize link in the browser
httpd.handle_request()
code = httpd.code
# Get the token
token = client.exchange_code_for_token(client_id=client_id, client_secret=client_secret, code=code)
# Now store that access token in the config
cfg.set("UserAcct", "Token", token)
with open("stravamng.cfg", "w") as cfg_file:
cfg.write(cfg_file)
client.access_token = token
# do stuff
athlete = client.get_athlete()
print("For {id}, I now have an access token {token}".format(id=athlete.id, token=token))
示例12: Strava
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
class Strava(object):
def __init__(self):
self.client_id = current_app.config['STRAVA_CLIENT_ID']
self.client_secret = current_app.config['STRAVA_CLIENT_SECRET']
self.redirect_uri = url_for('strava.confirm_auth', _external=True)
self.client = StravaClient()
self._activity_type = 'ride' # rides or runs
self._activities = None
@property
def activity_type(self):
return self._activity_type
@activity_type.setter
def activity_type(self, value):
self._activity_type = value
self._activities = None
@property
def athlete(self):
return self.client.get_athlete()
@property
def activities(self):
if not self._activities:
# current_year = datetime.datetime.now().year
# after = datetime.datetime(current_year - 2, 12, 25)
self._activities = Activities(self.client.get_activities(), self.activity_type)
return self._activities
@classmethod
def authorization_url(cls):
self = cls()
return self.client.authorization_url(client_id=self.client_id,
redirect_uri=self.redirect_uri)
def get_access_token(self, code):
return self.client.exchange_code_for_token(client_id=self.client_id,
client_secret=self.client_secret,
code=code)
@classmethod
def athlete_by_code(cls, code):
self = cls()
self.client.access_token = self.get_access_token(code)
return self.athlete
@classmethod
def athlete_by_token(cls, token):
self = cls()
self.client.access_token = token
return self.athlete
@classmethod
def activities_by_token(cls, token):
self = cls()
self.client.access_token = token
return self.activities
@classmethod
def by_token(cls, token):
self = cls()
self.client.access_token = token
return self
示例13: file
# 需要导入模块: from stravalib.client import Client [as 别名]
# 或者: from stravalib.client.Client import exchange_code_for_token [as 别名]
port = httpd.server_address[1]
authorize_url = client.authorization_url(
client_id=APP["id"],
redirect_uri="http://localhost:%d/authorized" % port,
scope="write")
print "Now open the following URL and authorise this application."
print "Then Strava should send you to a localhost:%d URL handled by this script." % port
print "If that fails, rerun this script passing the code= value as an argument."
print
print authorize_url
# "code" gets updated once Strava calls us back.
while not code:
httpd.handle_request()
access_token = client.exchange_code_for_token(
client_id=APP["id"],
client_secret=APP["client_secret"], code=code)
client.access_token = access_token
athlete = client.get_athlete()
print
print "Logged in as %s <%s>. Writing access token to file %s" % (athlete.firstname, athlete.email, FN)
f = file(FN, "w")
os.chmod(FN, 0600) # file won't do this as an extra argument, grrr
f.write(access_token)