diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c4ac62..db15a87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ # Changelog + All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), @@ -6,16 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased -### ... - - - ... - -## [2.12.1] - 2020-05-28 - -### Changed +### Added - Added two new attributes: error and error_description to `SpotifyOauthError` exception class to show authorization/authentication web api errors details. + - Allow extending `SpotifyClientCredentials` and `SpotifyOAuth` + +### Deprecated + + - Deprecated `util.prompt_for_user_token` in favor of `spotipy.Spotify(auth_manager=SpotifyOAuth())` ## [2.12.0] - 2020-04-26 diff --git a/FAQ.md b/FAQ.md index 465e8af..cefa18f 100644 --- a/FAQ.md +++ b/FAQ.md @@ -19,7 +19,7 @@ Solution: - Verify that you are signed in with the correct account on https://spotify.com - Remove your current token: `rm .cache-{userid}` - - Request a new token by adding `show_dialog=True` to `util.prompt_for_user_token(username,scope=scope,show_dialog=True)` + - Request a new token by adding `show_dialog=True` to `spotipy.Spotify(auth_manager=SpotifyOAuth(show_dialog=True))` - Check that `spotipy.me()` shows the correct user id ### 401 Unauthorized diff --git a/README.md b/README.md index b787f3c..75adf03 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,12 @@ Spotipy's full documentation is online at [Spotipy Documentation](http://spotipy pip install spotipy ``` +or upgrade + +```bash +pip install spotipy --upgrade +``` + ## Quick Start A full set of examples can be found in the [online documentation](http://spotipy.readthedocs.org/) and in the [Spotipy examples directory](https://github.com/plamere/spotipy/tree/master/examples). @@ -21,6 +27,8 @@ A full set of examples can be found in the [online documentation](http://spotipy To get started, install spotipy and create an app on https://developers.spotify.com/. Add your new ID and SECRET to your environment: +### Without user authentication + ```bash export SPOTIPY_CLIENT_ID=client_id_here export SPOTIPY_CLIENT_SECRET=client_secret_here @@ -28,19 +36,41 @@ export SPOTIPY_CLIENT_SECRET=client_secret_here // on Windows, use `SET` instead of `export` ``` -Then, create a Spotify object and call methods: - ```python import spotipy from spotipy.oauth2 import SpotifyClientCredentials -sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) +sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials()) results = sp.search(q='weezer', limit=20) for idx, track in enumerate(results['tracks']['items']): print(idx, track['name']) ``` +### With user authentication + +```bash +export SPOTIPY_CLIENT_ID=client_id_here +export SPOTIPY_CLIENT_SECRET=client_secret_here +export SPOTIPY_REDIRECT_URI=redirect_uri_here + +// on Windows, use `SET` instead of `export` +``` + +```python +import spotipy +from spotipy.oauth2 import SpotifyOAuth + +scope = "user-library-read" + +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + +results = sp.current_user_saved_tracks() +for idx, item in enumerate(results['items']): + track = item['track'] + print(idx, track['artists'][0]['name'], " – ", track['name']) +``` + ## Reporting Issues For common questions please check our [FAQ](FAQ.md). diff --git a/docs/index.rst b/docs/index.rst index 2c8f508..6dba018 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -3,6 +3,7 @@ Welcome to Spotipy! =================================== + *Spotipy* is a lightweight Python library for the `Spotify Web API `_. With *Spotipy* you get full access to all of the music data provided by the Spotify platform. @@ -50,7 +51,7 @@ artist's name:: import sys from spotipy.oauth2 import SpotifyClientCredentials - spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) + spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials()) if len(sys.argv) > 1: name = ' '.join(sys.argv[1:]) @@ -112,15 +113,23 @@ Since the token exchange involves sending your secret key, perform this on a secure location, like a backend service, and not from a client such as a browser or from a mobile app. -To support the **Authorization Code Flow** *Spotipy* provides a -utility method ``util.prompt_for_user_token`` that will attempt to authorize the -user. You can pass your app credentials directly into the method as arguments:: +Quick start +----------- - util.prompt_for_user_token(username, - scope, - client_id='your-spotify-client-id', - client_secret='your-spotify-client-secret', - redirect_uri='your-app-redirect-url') +To support the **Client Authorization Code Flow** *Spotipy* provides a +class SpotifyOAuth that can be used to authenticate requests like so:: + + import spotipy + from spotipy.oauth2 import SpotifyOAuth + + scope = "user-library-read" + + sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + + results = sp.current_user_saved_tracks() + for idx, item in enumerate(results['items']): + track = item['track'] + print(idx, track['artists'][0]['name'], " – ", track['name']) or if you are reluctant to immortalize your app credentials in your source code, you can set environment variables like so (use ``SET`` instead of ``export`` @@ -130,15 +139,17 @@ on Windows):: export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret' export SPOTIPY_REDIRECT_URI='your-app-redirect-url' -Call the ``util.prompt_for_user_token`` method with the username, the -desired scope (see `Using +Scopes +------ + +See `Using Scopes `_ for information -about scopes) and credentials (passed directly or via environment variables) -to start the authorization process. +about scopes. Redirect URI ------------ -For the **Authorization Code Flow** you need to add a **redirect URI** + +The **Authorization Code Flow** needs you to add a **redirect URI** to your application at `My Dashboard `_ (navigate to your application and then *[Edit Settings]*). @@ -146,51 +157,8 @@ to your application at The ``redirect_uri`` argument or ``SPOTIPY_REDIRECT_URI`` environment variable must match the redirect URI added to your application in your Dashboard. The redirect URI can be any valid URI (it does not need to be accessible) -such as ``http://example.com``, ``http://localhost`` or ``http://127.0.0.1:9090``. +such as ``http://example.com``, ``http://localhost`` or ``http://127.0.0.1:9090``. -Calling ``util.prompt_for_user_token`` will open Spotify's -application authorization page in your browser (and require you to log in -if you are not already logged in to spotify.com), unless a locally cached -access token exist from a previous authorization/authentication. - -After successful authentication your browser will be redirected to -the redirect URI of your application, e.g. ``http://localhost:9090/?code=``. - -If your request URI is set to ``http://127.0.0.1:`` or ``http://localhost:`` -Spotipy will automatically complete the authorization process -(obtain the ```` from the URI). - -If your request URI is set to any other URI you will need to manually copy the -URI from the browser's address bar and paste it into the terminal/console where -your Spotipy script is running (Spotipy will instruct you to do so). - -Example -------- - -Here's an example of getting user authorization to read a user's saved tracks:: - - import sys - import spotipy - import spotipy.util as util - - scope = 'user-library-read' - - if len(sys.argv) > 1: - username = sys.argv[1] - else: - print("Usage: %s username" % (sys.argv[0],)) - sys.exit() - - token = util.prompt_for_user_token(username, scope) - - if token: - sp = spotipy.Spotify(auth=token) - results = sp.current_user_saved_tracks() - for item in results['items']: - track = item['track'] - print(track['name'] + ' - ' + track['artists'][0]['name']) - else: - print("Can't get token for", username) Client Credentials Flow ======================= @@ -213,8 +181,8 @@ class SpotifyClientCredentials that can be used to authenticate requests like so import spotipy from spotipy.oauth2 import SpotifyClientCredentials - client_credentials_manager = SpotifyClientCredentials() - sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) + auth_manager = SpotifyClientCredentials() + sp = spotipy.Spotify(auth_manager=auth_manager) playlists = sp.user_playlists('spotify') while playlists: @@ -227,100 +195,26 @@ class SpotifyClientCredentials that can be used to authenticate requests like so IDs URIs and URLs -======================= +================= + *Spotipy* supports a number of different ID types: - - Spotify URI - The resource identifier that you can enter, for example, in + - **Spotify URI** - The resource identifier that you can enter, for example, in the Spotify Desktop client's search box to locate an artist, album, or - track. Example: spotify:track:6rqhFgbbKwnb9MLmUQDhG6 - - Spotify URL - An HTML link that opens a track, album, app, playlist or other + track. Example: ``spotify:track:6rqhFgbbKwnb9MLmUQDhG6`` + - **Spotify URL** - An HTML link that opens a track, album, app, playlist or other Spotify resource in a Spotify client. Example: - http://open.spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6 - - Spotify ID - A base-62 number that you can find at the end of the Spotify + ``http://open.spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6`` + - **Spotify ID** - A base-62 number that you can find at the end of the Spotify URI (see above) for an artist, track, album, etc. Example: - 6rqhFgbbKwnb9MLmUQDhG6 + ``6rqhFgbbKwnb9MLmUQDhG6`` In general, any *Spotipy* method that needs an artist, album, track or playlist ID will accept ids in any of the above form Examples -======== -Here are a few more examples of using *Spotipy*, this time using the Authorization Code Flow -to access your personal Spotify account data. - -Add tracks to a playlist:: - - import sys - - import spotipy - import spotipy.util as util - - if len(sys.argv) > 3: - username = sys.argv[1] - playlist_id = sys.argv[2] - track_ids = sys.argv[3:] - else: - print("Usage: %s username playlist_id track_id ..." % (sys.argv[0],)) - sys.exit() - - scope = 'playlist-modify-public' - token = util.prompt_for_user_token(username, scope) - - if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - results = sp.user_playlist_add_tracks(username, playlist_id, track_ids) - print(results) - else: - print("Can't get token for", username) - - -Shows the contents of every playlist owned by a user:: - - # shows a user's playlists (need to be authenticated via oauth) - - import sys - import spotipy - import spotipy.util as util - - def show_tracks(tracks): - for i, item in enumerate(tracks['items']): - track = item['track'] - print(" %d %32.32s %s" % (i, track['artists'][0]['name'], - track['name'])) - - - if __name__ == '__main__': - if len(sys.argv) > 1: - username = sys.argv[1] - else: - print("Whoops, need your username!") - print("usage: python user_playlists.py [username]") - sys.exit() - - token = util.prompt_for_user_token(username) - - if token: - sp = spotipy.Spotify(auth=token) - playlists = sp.user_playlists(username) - for playlist in playlists['items']: - if playlist['owner']['id'] == username: - print() - print(playlist['name']) - print (' total tracks', playlist['tracks']['total']) - results = sp.playlist(playlist['id'], - fields="tracks,next") - tracks = results['tracks'] - show_tracks(tracks) - while tracks['next']: - tracks = sp.next(tracks) - show_tracks(tracks) - else: - print("Can't get token for", username) - - -More Examples ======================= + There are many more examples of how to use *Spotipy* in the `Examples Directory `_ on Github @@ -368,6 +262,7 @@ If you think you've found a bug, let us know at Contribute ========== + Spotipy authored by Paul Lamere (plamere) with contributions by: - Daniel Beaudry // danbeaudry diff --git a/examples/add_a_saved_album.py b/examples/add_a_saved_album.py index b72c6db..04e762c 100644 --- a/examples/add_a_saved_album.py +++ b/examples/add_a_saved_album.py @@ -1,9 +1,8 @@ import argparse import logging -import os import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth logger = logging.getLogger('examples.add_a_saved_album') logging.basicConfig(level='DEBUG') @@ -13,9 +12,6 @@ scope = 'user-library-modify' def get_args(): parser = argparse.ArgumentParser(description='Creates a playlist for user') - parser.add_argument('-u', '--username', required=False, - default=os.environ.get('SPOTIPY_CLIENT_USERNAME'), - help='Username id. Defaults to environment var') parser.add_argument('-a', '--aids', action='append', required=True, help='Album ids') return parser.parse_args() @@ -23,13 +19,8 @@ def get_args(): def main(): args = get_args() - token = util.prompt_for_user_token(args.username, scope) - - if token: - sp = spotipy.Spotify(auth=token) - sp.current_user_saved_albums_add(albums=args.aids) - else: - logger.error("Can't get token for %s", args.username) + sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + sp.current_user_saved_albums_add(albums=args.aids) if __name__ == '__main__': diff --git a/examples/add_a_saved_track.py b/examples/add_a_saved_track.py index 781be01..84dbfe1 100644 --- a/examples/add_a_saved_track.py +++ b/examples/add_a_saved_track.py @@ -1,9 +1,8 @@ import argparse import logging -import os import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth scope = 'user-library-modify' @@ -14,9 +13,6 @@ logging.basicConfig(level='DEBUG') def get_args(): parser = argparse.ArgumentParser(description='Add tracks to Your ' 'Collection of saved tracks') - parser.add_argument('-u', '--username', required=False, - default=os.environ.get('SPOTIPY_CLIENT_USERNAME'), - help='Username id. Defaults to environment var') parser.add_argument('-t', '--tids', action='append', required=True, help='Track ids') return parser.parse_args() @@ -24,13 +20,9 @@ def get_args(): def main(): args = get_args() - token = util.prompt_for_user_token(args.username, scope) + sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) - if token: - sp = spotipy.Spotify(auth=token) - sp.current_user_saved_tracks_add(tracks=args.tids) - else: - logger.error("Can't get token for %s", args.username) + sp.current_user_saved_tracks_add(tracks=args.tids) if __name__ == '__main__': diff --git a/examples/add_tracks_to_playlist.py b/examples/add_tracks_to_playlist.py index ae61d81..ad997de 100644 --- a/examples/add_tracks_to_playlist.py +++ b/examples/add_tracks_to_playlist.py @@ -1,9 +1,8 @@ import argparse import logging -import os import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth logger = logging.getLogger('examples.add_tracks_to_playlist') logging.basicConfig(level='DEBUG') @@ -12,9 +11,6 @@ scope = 'playlist-modify-public' def get_args(): parser = argparse.ArgumentParser(description='Adds track to user playlist') - parser.add_argument('-u', '--username', required=False, - default=os.environ.get('SPOTIPY_CLIENT_USERNAME'), - help='Username id. Defaults to environment var') parser.add_argument('-t', '--tids', action='append', required=True, help='Track ids') parser.add_argument('-p', '--playlist', required=True, @@ -24,13 +20,10 @@ def get_args(): def main(): args = get_args() - token = util.prompt_for_user_token(args.username, scope) - if token: - sp = spotipy.Spotify(auth=token) - sp.user_playlist_add_tracks(args.username, args.playlist, args.tids) - else: - logger.error("Can't get token for %s", args.username) + sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + user_id = sp.me()['id'] + sp.user_playlist_add_tracks(user_id, args.playlist, args.tids) if __name__ == '__main__': diff --git a/examples/change_playlist_details.py b/examples/change_playlist_details.py index 62432c8..688eeba 100644 --- a/examples/change_playlist_details.py +++ b/examples/change_playlist_details.py @@ -1,9 +1,8 @@ import argparse import logging -import os import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth logger = logging.getLogger('examples.change_playlist_details') logging.basicConfig(level='DEBUG') @@ -13,9 +12,6 @@ scope = 'playlist-modify-public playlist-modify-private' def get_args(): parser = argparse.ArgumentParser(description='Modify details of playlist') - parser.add_argument('-u', '--username', required=False, - default=os.environ.get('SPOTIPY_CLIENT_USERNAME'), - help='Username id. Defaults to environment var') parser.add_argument('-p', '--playlist', required=True, help='Playlist id to alter details') parser.add_argument('-n', '--name', required=False, @@ -38,16 +34,14 @@ def get_args(): def main(): args = get_args() - token = util.prompt_for_user_token(args.username, scope) - if token: - sp = spotipy.Spotify(auth=token) - sp.user_playlist_change_details( - args.username, args.playlist, name=args.name, - public=args.public or args.private, - collaborative=args.collaborative or args.independent, - description=args.description) - else: - logger.error("Can't get token for %s", args.username) + sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + sp.user_playlist_change_details( + args.username, + args.playlist, + name=args.name, + public=args.public or args.private, + collaborative=args.collaborative or args.independent, + description=args.description) if __name__ == '__main__': diff --git a/examples/contains_a_saved_track.py b/examples/contains_a_saved_track.py index bd130b4..be85d83 100644 --- a/examples/contains_a_saved_track.py +++ b/examples/contains_a_saved_track.py @@ -2,23 +2,16 @@ import pprint import sys import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth scope = 'user-library-read' -if len(sys.argv) > 2: - username = sys.argv[1] - tids = sys.argv[2:] +if len(sys.argv) > 1: + tids = sys.argv[1] else: - print("Usage: %s username track-id ..." % (sys.argv[0],)) + print("Usage: %s track-id ..." % (sys.argv[0],)) sys.exit() -token = util.prompt_for_user_token(username, scope) - -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - results = sp.current_user_saved_tracks_contains(tracks=tids) + results = spotipy.current_user_saved_tracks_contains(tracks=tids) pprint.pprint(results) -else: - print("Can't get token for", username) + diff --git a/examples/create_playlist.py b/examples/create_playlist.py index dd60432..b9f38f9 100644 --- a/examples/create_playlist.py +++ b/examples/create_playlist.py @@ -1,10 +1,10 @@ # Creates a playlist for a user + import argparse import logging -import os import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth logger = logging.getLogger('examples.create_playlist') logging.basicConfig(level='DEBUG') @@ -12,9 +12,6 @@ logging.basicConfig(level='DEBUG') def get_args(): parser = argparse.ArgumentParser(description='Creates a playlist for user') - parser.add_argument('-u', '--username', required=False, - default=os.environ.get('SPOTIPY_CLIENT_USERNAME'), - help='Username id. Defaults to environment var') parser.add_argument('-p', '--playlist', required=True, help='Name of Playlist') parser.add_argument('-d', '--description', required=False, default='', @@ -25,14 +22,9 @@ def get_args(): def main(): args = get_args() scope = "playlist-modify-public" - token = util.prompt_for_user_token(args.username, scope) - - if token: - logger.info('USERNAME: %s, PLAYLIST: %s', args.username, args.playlist) - sp = spotipy.Spotify(auth=token) - sp.user_playlist_create(args.username, args.playlist) - else: - logger.error("Can't get token for: %s", args.username) + sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + user_id = sp.me()['id'] + sp.user_playlist_create(user_id, args.playlist) if __name__ == '__main__': diff --git a/examples/delete_a_saved_track.py b/examples/delete_a_saved_track.py index 7d40b6b..2550f61 100644 --- a/examples/delete_a_saved_track.py +++ b/examples/delete_a_saved_track.py @@ -4,23 +4,16 @@ import pprint import sys import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth scope = 'user-library-modify' -if len(sys.argv) > 2: - username = sys.argv[1] - tids = sys.argv[2:] +if len(sys.argv) > 1: + tids = sys.argv[1] else: - print("Usage: %s username track-id ..." % (sys.argv[0],)) + print("Usage: %s track-id ..." % (sys.argv[0],)) sys.exit() -token = util.prompt_for_user_token(username, scope) - -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False + sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) results = sp.current_user_saved_tracks_delete(tracks=tids) pprint.pprint(results) -else: - print("Can't get token for", username) diff --git a/examples/my_playlists.py b/examples/my_playlists.py index bd04b91..f55a225 100644 --- a/examples/my_playlists.py +++ b/examples/my_playlists.py @@ -1,24 +1,10 @@ # Shows a user's playlists -import sys - import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth -if len(sys.argv) > 1: - username = sys.argv[1] -else: - print("Usage: %s username" % (sys.argv[0],)) - sys.exit() +sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) -scope = '' -token = util.prompt_for_user_token(username, scope) - -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - results = sp.current_user_playlists(limit=50) - for i, item in enumerate(results['items']): - print("%d %s" % (i, item['name'])) -else: - print("Can't get token for", username) +results = sp.current_user_playlists(limit=50) +for i, item in enumerate(results['items']): + print("%d %s" % (i, item['name'])) \ No newline at end of file diff --git a/examples/my_top_artists.py b/examples/my_top_artists.py index dc8b873..e24ab08 100644 --- a/examples/my_top_artists.py +++ b/examples/my_top_artists.py @@ -1,28 +1,17 @@ # Shows the top artists for a user - -import sys - import spotipy -import spotipy.util as util - -if len(sys.argv) > 1: - username = sys.argv[1] -else: - print("Usage: %s username" % (sys.argv[0],)) - sys.exit() +from spotipy.oauth2 import SpotifyOAuth scope = 'user-top-read' -token = util.prompt_for_user_token(username, scope) +ranges = ['short_term', 'medium_term', 'long_term'] -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - ranges = ['short_term', 'medium_term', 'long_term'] - for range in ranges: - print("range:", range) - results = sp.current_user_top_artists(time_range=range, limit=50) - for i, item in enumerate(results['items']): - print(i, item['name']) - print() -else: - print("Can't get token for", username) +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + +for sp_range in ['short_term', 'medium_term', 'long_term']: + print("range:", sp_range) + + results = sp.current_user_top_artists(time_range=sp_range, limit=50) + + for i, item in enumerate(results['items']): + print(i, item['name']) + print() diff --git a/examples/my_top_tracks.py b/examples/my_top_tracks.py index 29782c8..f73e2b4 100644 --- a/examples/my_top_tracks.py +++ b/examples/my_top_tracks.py @@ -3,7 +3,7 @@ import sys import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth if len(sys.argv) > 1: username = sys.argv[1] @@ -12,18 +12,13 @@ else: sys.exit() scope = 'user-top-read' -token = util.prompt_for_user_token(username, scope) +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - ranges = ['short_term', 'medium_term', 'long_term'] - for range in ranges: - print("range:", range) - results = sp.current_user_top_tracks(time_range=range, limit=50) - for i, item in enumerate(results['items']): - print(i, item['name'], '//', item['artists'][0]['name']) - print() +ranges = ['short_term', 'medium_term', 'long_term'] -else: - print("Can't get token for", username) +for sp_range in ranges: + print("range:", sp_range) + results = sp.current_user_top_tracks(time_range=sp_range, limit=50) + for i, item in enumerate(results['items']): + print(i, item['name'], '//', item['artists'][0]['name']) + print() \ No newline at end of file diff --git a/examples/remove_specific_tracks_from_playlist.py b/examples/remove_specific_tracks_from_playlist.py index b2fce66..f93f280 100644 --- a/examples/remove_specific_tracks_from_playlist.py +++ b/examples/remove_specific_tracks_from_playlist.py @@ -1,17 +1,16 @@ -# removes tracks from a playlist +# Removes tracks from a playlist import pprint import sys import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth -if len(sys.argv) > 3: - username = sys.argv[1] - playlist_id = sys.argv[2] - track_ids_and_positions = sys.argv[3:] +if len(sys.argv) > 2: + playlist_id = sys.argv[1] + track_ids_and_positions = sys.argv[2:] track_ids = [] - for t_pos in sys.argv[3:]: + for t_pos in sys.argv[2:]: tid, pos = t_pos.split(',') track_ids.append({"uri": tid, "positions": [int(pos)]}) else: @@ -21,13 +20,10 @@ else: sys.exit() scope = 'playlist-modify-public' -token = util.prompt_for_user_token(username, scope) +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - results = sp.user_playlist_remove_specific_occurrences_of_tracks( - username, playlist_id, track_ids) - pprint.pprint(results) -else: - print("Can't get token for", username) +user_id = sp.me()['id'] + +results = sp.user_playlist_remove_specific_occurrences_of_tracks( + user_id, playlist_id, track_ids) +pprint.pprint(results) diff --git a/examples/remove_tracks_from_playlist.py b/examples/remove_tracks_from_playlist.py index c4efa1b..c7d6371 100644 --- a/examples/remove_tracks_from_playlist.py +++ b/examples/remove_tracks_from_playlist.py @@ -1,27 +1,24 @@ -# removes tracks to a playlist - +# Removes tracks from playlist import pprint import sys import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth -if len(sys.argv) > 3: - username = sys.argv[1] + +if len(sys.argv) > 2: playlist_id = sys.argv[2] track_ids = sys.argv[3:] else: - print("Usage: %s username playlist_id track_id ..." % (sys.argv[0],)) + print("Usage: %s playlist_id track_id ..." % (sys.argv[0])) sys.exit() scope = 'playlist-modify-public' -token = util.prompt_for_user_token(username, scope) -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - results = sp.user_playlist_remove_all_occurrences_of_tracks( - username, playlist_id, track_ids) - pprint.pprint(results) -else: - print("Can't get token for", username) +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + +user_id = sp.me()['id'] + +results = sp.user_playlist_remove_all_occurrences_of_tracks( + user_id, playlist_id, track_ids) +pprint.pprint(results) diff --git a/examples/replace_tracks_in_playlist.py b/examples/replace_tracks_in_playlist.py index d7236cc..8648ffb 100644 --- a/examples/replace_tracks_in_playlist.py +++ b/examples/replace_tracks_in_playlist.py @@ -4,23 +4,20 @@ import pprint import sys import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth if len(sys.argv) > 3: - username = sys.argv[1] - playlist_id = sys.argv[2] - track_ids = sys.argv[3:] + playlist_id = sys.argv[1] + track_ids = sys.argv[2:] else: print("Usage: %s username playlist_id track_id ..." % (sys.argv[0],)) sys.exit() scope = 'playlist-modify-public' -token = util.prompt_for_user_token(username, scope) -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - results = sp.user_playlist_replace_tracks(username, playlist_id, track_ids) - pprint.pprint(results) -else: - print("Can't get token for", username) +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) +user_id = sp.me()['id'] + +results = sp.user_playlist_replace_tracks(user_id, playlist_id, track_ids) +pprint.pprint(results) + diff --git a/examples/show_featured_playlists.py b/examples/show_featured_playlists.py index 769037c..d2d5965 100644 --- a/examples/show_featured_playlists.py +++ b/examples/show_featured_playlists.py @@ -1,32 +1,19 @@ # shows artist info for a URN or URL import spotipy -import sys -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth -if len(sys.argv) > 1: - username = sys.argv[1] -else: - print("Whoops, need your username!") - print("usage: python featured_playlists.py [username]") - sys.exit() +sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) -token = util.prompt_for_user_token(username) +response = sp.featured_playlists() +print(response['message']) -if token: - sp = spotipy.Spotify(auth=token) +while response: + playlists = response['playlists'] + for i, item in enumerate(playlists['items']): + print(playlists['offset'] + i, item['name']) - response = sp.featured_playlists() - print(response['message']) - - while response: - playlists = response['playlists'] - for i, item in enumerate(playlists['items']): - print(playlists['offset'] + i, item['name']) - - if playlists['next']: - response = sp.next(playlists) - else: - response = None -else: - print("Can't get token for", username) + if playlists['next']: + response = sp.next(playlists) + else: + response = None diff --git a/examples/show_my_saved_tracks.py b/examples/show_my_saved_tracks.py index 5ddab38..ebff4fe 100644 --- a/examples/show_my_saved_tracks.py +++ b/examples/show_my_saved_tracks.py @@ -1,17 +1,10 @@ -# shows a user's saved tracks (need to be authenticated via oauth) +# Shows a user's saved tracks (need to be authenticated via oauth) -import sys import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth scope = 'user-library-read' -if len(sys.argv) > 1: - username = sys.argv[1] -else: - print("Usage: %s username" % (sys.argv[0],)) - sys.exit() - def show_tracks(results): for item in results['items']: @@ -19,14 +12,11 @@ def show_tracks(results): print("%32.32s %s" % (track['artists'][0]['name'], track['name'])) -token = util.prompt_for_user_token(username, scope) +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) -if token: - sp = spotipy.Spotify(auth=token) - results = sp.current_user_saved_tracks() +results = sp.current_user_saved_tracks() +show_tracks(results) + +while results['next']: + results = sp.next(results) show_tracks(results) - while results['next']: - results = sp.next(results) - show_tracks(results) -else: - print("Can't get token for", username) diff --git a/examples/show_new_releases.py b/examples/show_new_releases.py index d4bd5fa..e4ab63e 100644 --- a/examples/show_new_releases.py +++ b/examples/show_new_releases.py @@ -1,31 +1,18 @@ # shows artist info for a URN or URL import spotipy -import sys -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth -if len(sys.argv) > 1: - username = sys.argv[1] -else: - print("Whoops, need your username!") - print("usage: python new_releases.py [username]") - sys.exit() +sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) -token = util.prompt_for_user_token(username) +response = sp.new_releases() -if token: - sp = spotipy.Spotify(auth=token) +while response: + albums = response['albums'] + for i, item in enumerate(albums['items']): + print(albums['offset'] + i, item['name']) - response = sp.new_releases() - - while response: - albums = response['albums'] - for i, item in enumerate(albums['items']): - print(albums['offset'] + i, item['name']) - - if albums['next']: - response = sp.next(albums) - else: - response = None -else: - print("Can't get token for", username) + if albums['next']: + response = sp.next(albums) + else: + response = None diff --git a/examples/test.py b/examples/test.py new file mode 100644 index 0000000..bffb19b --- /dev/null +++ b/examples/test.py @@ -0,0 +1,11 @@ +import spotipy +from spotipy.oauth2 import SpotifyOAuth + +scope = "user-library-read" + +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) + +results = sp.current_user_saved_tracks() +for idx, item in enumerate(results['items']): + track = item['track'] + print(idx, track['artists'][0]['name'], " – ", track['name']) diff --git a/examples/user_playlists.py b/examples/user_playlists.py index e94e810..4d75cb9 100644 --- a/examples/user_playlists.py +++ b/examples/user_playlists.py @@ -1,25 +1,10 @@ -# shows a user's playlists (need to be authenticated via oauth) - -import sys +# Shows a user's playlists (need to be authenticated via oauth) import spotipy +from spotipy.oauth2 import SpotifyOAuth -import spotipy.util as util +sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) +playlists = sp.current_user_playlists() - -if len(sys.argv) > 1: - username = sys.argv[1] -else: - print("Whoops, need your username!") - print("usage: python user_playlists.py [username]") - sys.exit() - -token = util.prompt_for_user_token(username) - -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) +for playlist in playlists['items']: + print(playlist['name']) diff --git a/examples/user_playlists_contents.py b/examples/user_playlists_contents.py index a36006a..8ffa9a3 100644 --- a/examples/user_playlists_contents.py +++ b/examples/user_playlists_contents.py @@ -1,8 +1,7 @@ -# shows a user's playlists (need to be authenticated via oauth) +# Shows a user's playlists (need to be authenticated via oauth) -import sys import spotipy -import spotipy.util as util +from spotipy.oauth2 import SpotifyOAuth def show_tracks(results): @@ -14,28 +13,21 @@ def show_tracks(results): if __name__ == '__main__': - if len(sys.argv) > 1: - username = sys.argv[1] - else: - print("Whoops, need your username!") - print("usage: python user_playlists_contents.py [username]") - sys.exit() + sp = spotipy.Spotify(auth_manager=SpotifyOAuth()) - token = util.prompt_for_user_token(username) + playlists = sp.current_user_playlists() + user_id = sp.me()['id'] - if token: - sp = spotipy.Spotify(auth=token) - playlists = sp.user_playlists(username) - for playlist in playlists['items']: - if playlist['owner']['id'] == username: - print() - print(playlist['name']) - print(' total tracks', playlist['tracks']['total']) - results = sp.playlist(playlist['id'], fields="tracks,next") - tracks = results['tracks'] + for playlist in playlists['items']: + if playlist['owner']['id'] == user_id: + print() + print(playlist['name']) + print(' total tracks', playlist['tracks']['total']) + + results = sp.playlist(playlist['id'], fields="tracks,next") + tracks = results['tracks'] + show_tracks(tracks) + + while tracks['next']: + tracks = sp.next(tracks) show_tracks(tracks) - while tracks['next']: - tracks = sp.next(tracks) - show_tracks(tracks) - else: - print("Can't get token for", username) diff --git a/examples/user_saved_albums_delete.py b/examples/user_saved_albums_delete.py index 783c33e..e071ee8 100644 --- a/examples/user_saved_albums_delete.py +++ b/examples/user_saved_albums_delete.py @@ -1,28 +1,12 @@ -""" - Deletes user saved album +# Deletes user saved album -""" - -import sys import spotipy -import spotipy.util as util - -if len(sys.argv) > 1: - username = sys.argv[1] -else: - print("Usage: %s username" % (sys.argv[0],)) - sys.exit() +from spotipy.oauth2 import SpotifyOAuth scope = 'user-library-modify' -token = util.prompt_for_user_token(username, scope) +sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) -if token: - sp = spotipy.Spotify(auth=token) - sp.trace = False - uris = input("input a list of album URIs, URLs or IDs: ") - uris = list(map(str, uris.split())) - deleted = sp.current_user_saved_albums_delete(uris) - print("Deletion successful.") - -else: - print("Can't get token for", username) +uris = input("input a list of album URIs, URLs or IDs: ") +uris = list(map(str, uris.split())) +deleted = sp.current_user_saved_albums_delete(uris) +print("Deletion successful.") diff --git a/spotipy/util.py b/spotipy/util.py index fad36c1..abc6025 100644 --- a/spotipy/util.py +++ b/spotipy/util.py @@ -6,6 +6,7 @@ __all__ = ["CLIENT_CREDS_ENV_VARS", "prompt_for_user_token"] import logging import os +import warnings import spotipy @@ -29,6 +30,13 @@ def prompt_for_user_token( oauth_manager=None, show_dialog=False ): + warnings.warn( + "'prompt_for_user_token' is deprecated." + "Use the following instead: " + " auth_manager=SpotifyOAuth(scope=scope)" + " spotipy.Spotify(auth_manager=auth_manager)", + DeprecationWarning + ) """ prompts the user to login if necessary and returns the user token suitable for use with the spotipy.Spotify constructor diff --git a/tests/integration/test_user_endpoints.py b/tests/integration/test_user_endpoints.py index fc4567c..7b70398 100644 --- a/tests/integration/test_user_endpoints.py +++ b/tests/integration/test_user_endpoints.py @@ -264,7 +264,7 @@ class SpotipyUserApiTests(unittest.TestCase): def test_current_user_top_artists(self): response = self.spotify.current_user_top_artists() items = response['items'] - self.assertGreater(len(items), 0) + self.assertGreaterEqual(len(items), 0) class SpotipyBrowseApiTests(unittest.TestCase):