Don't use cached tokens when scope changes

This commit is contained in:
Paul Lamere 2014-07-07 17:03:27 +02:00
parent 4f6aef7e79
commit 75a3779779
4 changed files with 34 additions and 2 deletions

View File

@ -1,4 +1,6 @@
v1.40, June 12, 2014 -- Initial public release.
v1.42, June 19, 2014 -- Removed dependency on simplejson
v1.43, June 27, 2014 -- Fixed JSON handling issue
v1.44, July 3, 2014 -- Added show_tracks.py exampole
v1.45, July 7, 2014 -- Don't used cache auth codes when scope changes

View File

@ -3,6 +3,7 @@
import os
import subprocess
import sys
import spotipy.oauth2 as oauth2
def prompt_for_user_token(username, scope=None):
@ -15,6 +16,20 @@ def prompt_for_user_token(username, scope=None):
client_secret = os.getenv('CLIENT_SECRET', 'YOUR_CLIENT_SECRET')
redirect_uri = os.getenv('REDIRECT_URI', 'YOUR_REDIRECT_URI')
if client_id == 'YOUR_CLIENT_ID':
print '''
You need to set your Spotify API credentials. You can do this by
setting environment variables like so:
export CLIENT_ID='your-spotify-client-id'
export CLIENT_SECRET='your-spotify-client-secret'
export REDIRECT_URI='your-app-redirect-url'
Get your credentials at https://developer.spotify.com/my-applications
'''
sys.exit(1)
sp_oauth = oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri,
scope=scope, cache_path=username)

View File

@ -3,7 +3,7 @@ from setuptools import setup
setup(
name='SpotipyWebApi',
version='1.44',
version='1.45',
description='simple client for the Spotify Web API',
author="@plamere",
author_email="paul@echonest.com",

View File

@ -22,8 +22,8 @@ class SpotifyOAuth(object):
self.client_secret = client_secret
self.redirect_uri = redirect_uri
self.state=state
self.scope=scope
self.cache_path = cache_path
self.scope=self.normalize_scope(scope)
def get_cached_token(self):
token_info = None
@ -33,8 +33,14 @@ class SpotifyOAuth(object):
token_info_string = f.read()
f.close()
token_info = json.loads(token_info_string)
# if scopes don't match, then bail
if 'scope' not in token_info or self.scope != token_info['scope']:
return None
if self.is_token_expired(token_info):
new_token_info = self.refresh_access_token(token_info['refresh_token'])
except IOError:
pass
return token_info
@ -86,9 +92,18 @@ class SpotifyOAuth(object):
raise SpotifyOauthError(response.reason)
token_info = response.json()
token_info['expires_at'] = int(time.time()) + token_info['expires_in']
token_info['scope'] = self.scope
self.save_token_info(token_info)
return token_info
def normalize_scope(self, scope):
if scope:
scopes = scope.split()
scopes.sort()
return ' '.join(scopes)
else:
return None
def refresh_access_token(self, refresh_token):
payload = { 'refresh_token': refresh_token,
'grant_type': 'refresh_token'}