Added support for token caching and refresh

This commit is contained in:
Paul Lamere 2014-05-20 08:30:48 -04:00
parent 802c4b4354
commit 6ed7860b9d
2 changed files with 74 additions and 20 deletions

View File

@ -17,29 +17,37 @@ else:
# Create these via developer.spotify.com/my-applications
client_id = os.getenv('CLIENT_ID')
client_secret = os.getenv('CLIENT_SECRET')
redirect_uri = os.getenv('REDIRECT_URI')
client_id = os.getenv('CLIENT_ID', 'YOUR_CLIENT_ID')
client_secret = os.getenv('CLIENT_SECRET', 'YOUR_CLIENT_SECRET')
redirect_uri = os.getenv('REDIRECT_URI', 'YOUR_REDIRECT_URI')
print 'client_id', client_id
print 'client_secret', client_secret
print 'redirect_uri', redirect_uri
# Oauth flow
sp_oauth = oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri)
auth_url = sp_oauth.get_authorize_url()
try:
subprocess.call(["open", auth_url])
print "Opening %s in your browser" % auth_url
except:
print "Please navigate here: %s" % auth_url
sp_oauth = oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, cache_path=username)
response = raw_input("The URL you were redirected to: ")
code = sp_oauth.parse_response_code(response)
access_token = sp_oauth.get_access_token(code)
# try to get a valid token for this user, from the cache,
# if not in the cache, the create a new (this will send
# the user to a web page where they can authorize this app)
token_info = sp_oauth.get_cached_token()
if not token_info:
auth_url = sp_oauth.get_authorize_url()
try:
subprocess.call(["open", auth_url])
print "Opening %s in your browser" % auth_url
except:
print "Please navigate here: %s" % auth_url
response = raw_input("The URL you were redirected to: ")
code = sp_oauth.parse_response_code(response)
token_info = sp_oauth.get_access_token(code)
# Auth'ed API request
sp = spotipy.Spotify(auth=token_info['access_token'])
sp = spotipy.Spotify(auth=access_token)
playlists = sp.user_playlists(username)
pprint.pprint(playlists)
for playlist in playlists['items']:
print playlist['name']

View File

@ -1,8 +1,9 @@
import base64
import urllib
import requests
print ('oauth2 is here')
import os
import simplejson as json
import time
class SpotifyOauthError(Exception):
pass
@ -15,13 +16,39 @@ class SpotifyOAuth(object):
OAUTH_AUTHORIZE_URL = 'https://accounts.spotify.com/authorize'
OAUTH_TOKEN_URL = 'https://accounts.spotify.com/api/token'
def __init__(self, client_id, client_secret, redirect_uri, state=None, scope=None):
def __init__(self, client_id, client_secret, redirect_uri, state=None, scope=None, cache_path=None):
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
self.state=state
self.scope=scope
self.cache_path = cache_path
def get_cached_token(self):
token_info = None
if self.cache_path:
try:
f = open(self.cache_path)
token_info_string = f.read()
f.close()
token_info = json.loads(token_info_string)
if self.is_token_expired(token_info):
new_token_info = self.refresh_access_token(token_info['refresh_token'])
except IOError:
pass
return token_info
def save_token_info(self, token_info):
if self.cache_path:
f = open(self.cache_path, 'w')
print >>f, json.dumps(token_info)
f.close()
def is_token_expired(self, token_info):
now = int(time.time())
return token_info['expires_at'] < now
def get_authorize_url(self):
payload = {'client_id': self.client_id,
'response_type': 'code',
@ -54,4 +81,23 @@ class SpotifyOAuth(object):
response = requests.post(self.OAUTH_TOKEN_URL, data=payload, headers=headers, verify=True)
if response.status_code is not 200:
raise SpotifyOauthError(response.reason)
return response.json()['access_token']
token_info = response.json()
token_info['expires_at'] = int(time.time()) + token_info['expires_in']
self.save_token_info(token_info)
return token_info
def refresh_access_token(self, refresh_token):
payload = { 'refresh_token': refresh_token,
'grant_type': 'refresh_token'}
auth_header = base64.b64encode(self.client_id + ':' + self.client_secret)
headers = {'Authorization': 'Basic %s' % auth_header}
response = requests.post(self.OAUTH_TOKEN_URL, data=payload, headers=headers, verify=True)
if response.status_code is not 200:
raise SpotifyOauthError(response.reason)
token_info = response.json()
token_info['expires_at'] = int(time.time()) + token_info['expires_in']
token_info['refresh_token'] = refresh_token
self.save_token_info(token_info)
return token_info