improved oauth examples

This commit is contained in:
Paul Lamere 2014-05-23 07:19:16 -04:00
parent edbf23a20f
commit 539c9fb652
3 changed files with 20 additions and 39 deletions

View File

@ -6,8 +6,12 @@ import os
import subprocess
import spotipy
import util
import spotipy.oauth2 as oauth2
if len(sys.argv) > 1:
username = sys.argv[1]
else:
@ -15,39 +19,12 @@ else:
print "usage: python user_playlists.py [username]"
sys.exit()
# Create these via developer.spotify.com/my-applications
token = util.prompt_for_user_token(username)
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
sp_oauth = oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, cache_path=username)
# 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'])
playlists = sp.user_playlists(username)
for playlist in playlists['items']:
print playlist['name']
if token:
sp = spotipy.Spotify(auth=token)
playlists = sp.user_playlists(username)
for playlist in playlists['items']:
print playlist['name']
else:
print "Can't get token for", username

View File

@ -174,10 +174,10 @@ class Spotify(object):
'''
return self.get("users/%s/playlists" % user)
def user_playlist(self, user, playlist_id):
def user_playlist(self, user, playlist_id, fields=None):
''' Gets playlist of a user
'''
return self.get("users/%s/playlists/%s" % (user, playlist_id))
return self.get("users/%s/playlists/%s" % (user, playlist_id), fields=fields)
def me(self):
''' returns info about me

View File

@ -63,7 +63,10 @@ class SpotifyOAuth(object):
return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams)
def parse_response_code(self, response):
return response.split("?code=")[1].split("&")[0]
try:
return response.split("?code=")[1].split("&")[0]
except IndexError:
return None
def get_access_token(self, code):
payload = {'redirect_uri': self.redirect_uri,
@ -97,7 +100,8 @@ class SpotifyOAuth(object):
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
if not 'refresh_token' in token_info:
token_info['refresh_token'] = refresh_token
self.save_token_info(token_info)
return token_info