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

@@ -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