From 9988c98b2e1b0c3c064f7399745eb21e61463034 Mon Sep 17 00:00:00 2001 From: Paul Lamere Date: Mon, 19 May 2014 06:49:08 -0400 Subject: [PATCH] Added paging support and example. --- examples/artist_discography.py | 58 ++++++++++++++++++++++++++++++++++ spotipy/__init__.py | 21 +++++++++++- 2 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 examples/artist_discography.py diff --git a/examples/artist_discography.py b/examples/artist_discography.py new file mode 100644 index 0000000..a0dc72e --- /dev/null +++ b/examples/artist_discography.py @@ -0,0 +1,58 @@ + +import sys +import spotipy + +''' shows the albums and tracks for a given artist. +''' + +def get_artist(name): + results = sp.search(q='artist:' + name, type='artist') + items = results['artists']['items'] + if len(items) > 0: + return items[0] + else: + return None + +def show_album_tracks(album): + tracks = [] + results = sp.album_tracks(album['id']) + tracks.extend(results['items']) + while results['next']: + results = sp.next(results) + tracks.extend(results['items']) + for track in tracks: + print ' ', track['name'] + +def show_artist_albums(id): + albums = [] + results = sp.artist_albums(artist['id'], album_type='album') + albums.extend(results['items']) + while results['next']: + results = sp.next(results) + albums.extend(results['items']) + print 'Total albums:', len(albums) + unique = set() # skip duplicate albums + for album in albums: + name = album['name'] + if not name in unique: + print name + unique.add(name) + show_album_tracks(album) + +def show_artist(artist): + print '====', artist['name'], '====' + print 'Popularity: ', artist['popularity'] + if len(artist['genres']) > 0: + print 'Genres: ', ','.join(artist['genres']) + +if __name__ == '__main__': + sp = spotipy.Spotify() + sp.trace = False + + if len(sys.argv) < 2: + print('Usage: {0} artist name'.format(sys.argv[0])) + else: + name = ' '.join(sys.argv[1:]) + artist = get_artist(name) + show_artist(artist) + show_artist_albums(artist) diff --git a/spotipy/__init__.py b/spotipy/__init__.py index 3f77646..0efdb5e 100644 --- a/spotipy/__init__.py +++ b/spotipy/__init__.py @@ -53,7 +53,10 @@ class Spotify(object): return None def _internal_call(self, verb, method, params): - url = self.prefix + method + if not method.startswith('http'): + url = self.prefix + method + else: + url = method args = dict(params=params) headers = self._auth_headers() r = requests.request(verb, url, headers=headers, **args) @@ -73,6 +76,22 @@ class Spotify(object): kwargs.update(args) return self._internal_call('GET', method, kwargs) + def next(self, result): + ''' returns the next result given a result + ''' + if result['next']: + return self.get(result['next']) + else: + return None + + def previous(self, result): + ''' returns the previous result given a result + ''' + if result['previous']: + return self.get(result['previous']) + else: + return None + def _warn(self, msg): print('warning:' + msg, file=sys.stderr)