Deprecate util.prompt_for_user_token()

This commit is contained in:
Stephane Bruckert 2020-06-14 18:01:14 +01:00
parent 587baec9b9
commit c7f2edf343
26 changed files with 254 additions and 477 deletions

View File

@ -1,4 +1,5 @@
# Changelog # Changelog
All notable changes to this project will be documented in this file. 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/), 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 ## Unreleased
### ... ### Added
- ...
## [2.12.1] - 2020-05-28
### Changed
- Added two new attributes: error and error_description to `SpotifyOauthError` exception class to show - Added two new attributes: error and error_description to `SpotifyOauthError` exception class to show
authorization/authentication web api errors details. 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 ## [2.12.0] - 2020-04-26

2
FAQ.md
View File

@ -19,7 +19,7 @@ Solution:
- Verify that you are signed in with the correct account on https://spotify.com - Verify that you are signed in with the correct account on https://spotify.com
- Remove your current token: `rm .cache-{userid}` - 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 - Check that `spotipy.me()` shows the correct user id
### 401 Unauthorized ### 401 Unauthorized

View File

@ -14,6 +14,12 @@ Spotipy's full documentation is online at [Spotipy Documentation](http://spotipy
pip install spotipy pip install spotipy
``` ```
or upgrade
```bash
pip install spotipy --upgrade
```
## Quick Start ## 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). 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/. To get started, install spotipy and create an app on https://developers.spotify.com/.
Add your new ID and SECRET to your environment: Add your new ID and SECRET to your environment:
### Without user authentication
```bash ```bash
export SPOTIPY_CLIENT_ID=client_id_here export SPOTIPY_CLIENT_ID=client_id_here
export SPOTIPY_CLIENT_SECRET=client_secret_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` // on Windows, use `SET` instead of `export`
``` ```
Then, create a Spotify object and call methods:
```python ```python
import spotipy import spotipy
from spotipy.oauth2 import SpotifyClientCredentials 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) results = sp.search(q='weezer', limit=20)
for idx, track in enumerate(results['tracks']['items']): for idx, track in enumerate(results['tracks']['items']):
print(idx, track['name']) 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 ## Reporting Issues
For common questions please check our [FAQ](FAQ.md). For common questions please check our [FAQ](FAQ.md).

View File

@ -3,6 +3,7 @@
Welcome to Spotipy! Welcome to Spotipy!
=================================== ===================================
*Spotipy* is a lightweight Python library for the `Spotify Web API *Spotipy* is a lightweight Python library for the `Spotify Web API
<https://developer.spotify.com/web-api/>`_. With *Spotipy* <https://developer.spotify.com/web-api/>`_. With *Spotipy*
you get full access to all of the music data provided by the Spotify platform. you get full access to all of the music data provided by the Spotify platform.
@ -50,7 +51,7 @@ artist's name::
import sys import sys
from spotipy.oauth2 import SpotifyClientCredentials from spotipy.oauth2 import SpotifyClientCredentials
spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
if len(sys.argv) > 1: if len(sys.argv) > 1:
name = ' '.join(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 secure location, like a backend service, and not from a client such as a
browser or from a mobile app. browser or from a mobile app.
To support the **Authorization Code Flow** *Spotipy* provides a Quick start
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::
util.prompt_for_user_token(username, To support the **Client Authorization Code Flow** *Spotipy* provides a
scope, class SpotifyOAuth that can be used to authenticate requests like so::
client_id='your-spotify-client-id',
client_secret='your-spotify-client-secret', import spotipy
redirect_uri='your-app-redirect-url') 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, 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`` 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_CLIENT_SECRET='your-spotify-client-secret'
export SPOTIPY_REDIRECT_URI='your-app-redirect-url' export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
Call the ``util.prompt_for_user_token`` method with the username, the Scopes
desired scope (see `Using ------
See `Using
Scopes <https://developer.spotify.com/web-api/using-scopes/>`_ for information Scopes <https://developer.spotify.com/web-api/using-scopes/>`_ for information
about scopes) and credentials (passed directly or via environment variables) about scopes.
to start the authorization process.
Redirect URI 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 to your application at
`My Dashboard <https://developer.spotify.com/dashboard/applications>`_ `My Dashboard <https://developer.spotify.com/dashboard/applications>`_
(navigate to your application and then *[Edit Settings]*). (navigate to your application and then *[Edit Settings]*).
@ -148,49 +159,6 @@ 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) 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=<code>``.
If your request URI is set to ``http://127.0.0.1:<port>`` or ``http://localhost:<port>``
Spotipy will automatically complete the authorization process
(obtain the ``<code>`` 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 Client Credentials Flow
======================= =======================
@ -213,8 +181,8 @@ class SpotifyClientCredentials that can be used to authenticate requests like so
import spotipy import spotipy
from spotipy.oauth2 import SpotifyClientCredentials from spotipy.oauth2 import SpotifyClientCredentials
client_credentials_manager = SpotifyClientCredentials() auth_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) sp = spotipy.Spotify(auth_manager=auth_manager)
playlists = sp.user_playlists('spotify') playlists = sp.user_playlists('spotify')
while playlists: while playlists:
@ -227,100 +195,26 @@ class SpotifyClientCredentials that can be used to authenticate requests like so
IDs URIs and URLs IDs URIs and URLs
======================= =================
*Spotipy* supports a number of different ID types: *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 the Spotify Desktop client's search box to locate an artist, album, or
track. Example: spotify:track:6rqhFgbbKwnb9MLmUQDhG6 track. Example: ``spotify:track:6rqhFgbbKwnb9MLmUQDhG6``
- Spotify URL - An HTML link that opens a track, album, app, playlist or other - **Spotify URL** - An HTML link that opens a track, album, app, playlist or other
Spotify resource in a Spotify client. Example: Spotify resource in a Spotify client. Example:
http://open.spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6 ``http://open.spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6``
- Spotify ID - A base-62 number that you can find at the end of the Spotify - **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: 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 In general, any *Spotipy* method that needs an artist, album, track or playlist ID
will accept ids in any of the above form will accept ids in any of the above form
Examples 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 There are many more examples of how to use *Spotipy* in the `Examples
Directory <https://github.com/plamere/spotipy/tree/master/examples>`_ on Github Directory <https://github.com/plamere/spotipy/tree/master/examples>`_ on Github
@ -368,6 +262,7 @@ If you think you've found a bug, let us know at
Contribute Contribute
========== ==========
Spotipy authored by Paul Lamere (plamere) with contributions by: Spotipy authored by Paul Lamere (plamere) with contributions by:
- Daniel Beaudry // danbeaudry - Daniel Beaudry // danbeaudry

View File

@ -1,9 +1,8 @@
import argparse import argparse
import logging import logging
import os
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
logger = logging.getLogger('examples.add_a_saved_album') logger = logging.getLogger('examples.add_a_saved_album')
logging.basicConfig(level='DEBUG') logging.basicConfig(level='DEBUG')
@ -13,9 +12,6 @@ scope = 'user-library-modify'
def get_args(): def get_args():
parser = argparse.ArgumentParser(description='Creates a playlist for user') 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', parser.add_argument('-a', '--aids', action='append',
required=True, help='Album ids') required=True, help='Album ids')
return parser.parse_args() return parser.parse_args()
@ -23,13 +19,8 @@ def get_args():
def main(): def main():
args = get_args() 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_albums_add(albums=args.aids) sp.current_user_saved_albums_add(albums=args.aids)
else:
logger.error("Can't get token for %s", args.username)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,9 +1,8 @@
import argparse import argparse
import logging import logging
import os
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
scope = 'user-library-modify' scope = 'user-library-modify'
@ -14,9 +13,6 @@ logging.basicConfig(level='DEBUG')
def get_args(): def get_args():
parser = argparse.ArgumentParser(description='Add tracks to Your ' parser = argparse.ArgumentParser(description='Add tracks to Your '
'Collection of saved tracks') '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', parser.add_argument('-t', '--tids', action='append',
required=True, help='Track ids') required=True, help='Track ids')
return parser.parse_args() return parser.parse_args()
@ -24,13 +20,9 @@ def get_args():
def main(): def main():
args = get_args() 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) sp.current_user_saved_tracks_add(tracks=args.tids)
else:
logger.error("Can't get token for %s", args.username)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,9 +1,8 @@
import argparse import argparse
import logging import logging
import os
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
logger = logging.getLogger('examples.add_tracks_to_playlist') logger = logging.getLogger('examples.add_tracks_to_playlist')
logging.basicConfig(level='DEBUG') logging.basicConfig(level='DEBUG')
@ -12,9 +11,6 @@ scope = 'playlist-modify-public'
def get_args(): def get_args():
parser = argparse.ArgumentParser(description='Adds track to user playlist') 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', parser.add_argument('-t', '--tids', action='append',
required=True, help='Track ids') required=True, help='Track ids')
parser.add_argument('-p', '--playlist', required=True, parser.add_argument('-p', '--playlist', required=True,
@ -24,13 +20,10 @@ def get_args():
def main(): def main():
args = get_args() args = get_args()
token = util.prompt_for_user_token(args.username, scope)
if token: sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
sp = spotipy.Spotify(auth=token) user_id = sp.me()['id']
sp.user_playlist_add_tracks(args.username, args.playlist, args.tids) sp.user_playlist_add_tracks(user_id, args.playlist, args.tids)
else:
logger.error("Can't get token for %s", args.username)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,9 +1,8 @@
import argparse import argparse
import logging import logging
import os
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
logger = logging.getLogger('examples.change_playlist_details') logger = logging.getLogger('examples.change_playlist_details')
logging.basicConfig(level='DEBUG') logging.basicConfig(level='DEBUG')
@ -13,9 +12,6 @@ scope = 'playlist-modify-public playlist-modify-private'
def get_args(): def get_args():
parser = argparse.ArgumentParser(description='Modify details of playlist') 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, parser.add_argument('-p', '--playlist', required=True,
help='Playlist id to alter details') help='Playlist id to alter details')
parser.add_argument('-n', '--name', required=False, parser.add_argument('-n', '--name', required=False,
@ -38,16 +34,14 @@ def get_args():
def main(): def main():
args = get_args() 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.user_playlist_change_details( sp.user_playlist_change_details(
args.username, args.playlist, name=args.name, args.username,
args.playlist,
name=args.name,
public=args.public or args.private, public=args.public or args.private,
collaborative=args.collaborative or args.independent, collaborative=args.collaborative or args.independent,
description=args.description) description=args.description)
else:
logger.error("Can't get token for %s", args.username)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -2,23 +2,16 @@ import pprint
import sys import sys
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
scope = 'user-library-read' scope = 'user-library-read'
if len(sys.argv) > 2: if len(sys.argv) > 1:
username = sys.argv[1] tids = sys.argv[1]
tids = sys.argv[2:]
else: else:
print("Usage: %s username track-id ..." % (sys.argv[0],)) print("Usage: %s track-id ..." % (sys.argv[0],))
sys.exit() sys.exit()
token = util.prompt_for_user_token(username, scope) results = spotipy.current_user_saved_tracks_contains(tracks=tids)
if token:
sp = spotipy.Spotify(auth=token)
sp.trace = False
results = sp.current_user_saved_tracks_contains(tracks=tids)
pprint.pprint(results) pprint.pprint(results)
else:
print("Can't get token for", username)

View File

@ -1,10 +1,10 @@
# Creates a playlist for a user # Creates a playlist for a user
import argparse import argparse
import logging import logging
import os
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
logger = logging.getLogger('examples.create_playlist') logger = logging.getLogger('examples.create_playlist')
logging.basicConfig(level='DEBUG') logging.basicConfig(level='DEBUG')
@ -12,9 +12,6 @@ logging.basicConfig(level='DEBUG')
def get_args(): def get_args():
parser = argparse.ArgumentParser(description='Creates a playlist for user') 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, parser.add_argument('-p', '--playlist', required=True,
help='Name of Playlist') help='Name of Playlist')
parser.add_argument('-d', '--description', required=False, default='', parser.add_argument('-d', '--description', required=False, default='',
@ -25,14 +22,9 @@ def get_args():
def main(): def main():
args = get_args() args = get_args()
scope = "playlist-modify-public" scope = "playlist-modify-public"
token = util.prompt_for_user_token(args.username, scope) sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
user_id = sp.me()['id']
if token: sp.user_playlist_create(user_id, args.playlist)
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)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -4,23 +4,16 @@ import pprint
import sys import sys
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
scope = 'user-library-modify' scope = 'user-library-modify'
if len(sys.argv) > 2: if len(sys.argv) > 1:
username = sys.argv[1] tids = sys.argv[1]
tids = sys.argv[2:]
else: else:
print("Usage: %s username track-id ..." % (sys.argv[0],)) print("Usage: %s track-id ..." % (sys.argv[0],))
sys.exit() sys.exit()
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.current_user_saved_tracks_delete(tracks=tids) results = sp.current_user_saved_tracks_delete(tracks=tids)
pprint.pprint(results) pprint.pprint(results)
else:
print("Can't get token for", username)

View File

@ -1,24 +1,10 @@
# Shows a user's playlists # Shows a user's playlists
import sys
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
if len(sys.argv) > 1: sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
username = sys.argv[1]
else:
print("Usage: %s username" % (sys.argv[0],))
sys.exit()
scope = '' results = sp.current_user_playlists(limit=50)
token = util.prompt_for_user_token(username, scope) for i, item in enumerate(results['items']):
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'])) print("%d %s" % (i, item['name']))
else:
print("Can't get token for", username)

View File

@ -1,28 +1,17 @@
# Shows the top artists for a user # Shows the top artists for a user
import sys
import spotipy 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()
scope = 'user-top-read' scope = 'user-top-read'
token = util.prompt_for_user_token(username, scope) ranges = ['short_term', 'medium_term', 'long_term']
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)
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']): for i, item in enumerate(results['items']):
print(i, item['name']) print(i, item['name'])
print() print()
else:
print("Can't get token for", username)

View File

@ -3,7 +3,7 @@
import sys import sys
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
if len(sys.argv) > 1: if len(sys.argv) > 1:
username = sys.argv[1] username = sys.argv[1]
@ -12,18 +12,13 @@ else:
sys.exit() sys.exit()
scope = 'user-top-read' scope = 'user-top-read'
token = util.prompt_for_user_token(username, scope) sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
if token: ranges = ['short_term', 'medium_term', 'long_term']
sp = spotipy.Spotify(auth=token)
sp.trace = False for sp_range in ranges:
ranges = ['short_term', 'medium_term', 'long_term'] print("range:", sp_range)
for range in ranges: results = sp.current_user_top_tracks(time_range=sp_range, limit=50)
print("range:", range)
results = sp.current_user_top_tracks(time_range=range, limit=50)
for i, item in enumerate(results['items']): for i, item in enumerate(results['items']):
print(i, item['name'], '//', item['artists'][0]['name']) print(i, item['name'], '//', item['artists'][0]['name'])
print() print()
else:
print("Can't get token for", username)

View File

@ -1,17 +1,16 @@
# removes tracks from a playlist # Removes tracks from a playlist
import pprint import pprint
import sys import sys
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
if len(sys.argv) > 3: if len(sys.argv) > 2:
username = sys.argv[1] playlist_id = sys.argv[1]
playlist_id = sys.argv[2] track_ids_and_positions = sys.argv[2:]
track_ids_and_positions = sys.argv[3:]
track_ids = [] track_ids = []
for t_pos in sys.argv[3:]: for t_pos in sys.argv[2:]:
tid, pos = t_pos.split(',') tid, pos = t_pos.split(',')
track_ids.append({"uri": tid, "positions": [int(pos)]}) track_ids.append({"uri": tid, "positions": [int(pos)]})
else: else:
@ -21,13 +20,10 @@ else:
sys.exit() sys.exit()
scope = 'playlist-modify-public' scope = 'playlist-modify-public'
token = util.prompt_for_user_token(username, scope) sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
if token: user_id = sp.me()['id']
sp = spotipy.Spotify(auth=token)
sp.trace = False results = sp.user_playlist_remove_specific_occurrences_of_tracks(
results = sp.user_playlist_remove_specific_occurrences_of_tracks( user_id, playlist_id, track_ids)
username, playlist_id, track_ids) pprint.pprint(results)
pprint.pprint(results)
else:
print("Can't get token for", username)

View File

@ -1,27 +1,24 @@
# removes tracks to a playlist # Removes tracks from playlist
import pprint import pprint
import sys import sys
import spotipy 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] playlist_id = sys.argv[2]
track_ids = sys.argv[3:] track_ids = sys.argv[3:]
else: else:
print("Usage: %s username playlist_id track_id ..." % (sys.argv[0],)) print("Usage: %s playlist_id track_id ..." % (sys.argv[0]))
sys.exit() sys.exit()
scope = 'playlist-modify-public' scope = 'playlist-modify-public'
token = util.prompt_for_user_token(username, scope)
if token: sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
sp = spotipy.Spotify(auth=token)
sp.trace = False user_id = sp.me()['id']
results = sp.user_playlist_remove_all_occurrences_of_tracks(
username, playlist_id, track_ids) results = sp.user_playlist_remove_all_occurrences_of_tracks(
pprint.pprint(results) user_id, playlist_id, track_ids)
else: pprint.pprint(results)
print("Can't get token for", username)

View File

@ -4,23 +4,20 @@ import pprint
import sys import sys
import spotipy import spotipy
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
if len(sys.argv) > 3: if len(sys.argv) > 3:
username = sys.argv[1] playlist_id = sys.argv[1]
playlist_id = sys.argv[2] track_ids = sys.argv[2:]
track_ids = sys.argv[3:]
else: else:
print("Usage: %s username playlist_id track_id ..." % (sys.argv[0],)) print("Usage: %s username playlist_id track_id ..." % (sys.argv[0],))
sys.exit() sys.exit()
scope = 'playlist-modify-public' scope = 'playlist-modify-public'
token = util.prompt_for_user_token(username, scope)
if token: sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
sp = spotipy.Spotify(auth=token) user_id = sp.me()['id']
sp.trace = False
results = sp.user_playlist_replace_tracks(username, playlist_id, track_ids) results = sp.user_playlist_replace_tracks(user_id, playlist_id, track_ids)
pprint.pprint(results) pprint.pprint(results)
else:
print("Can't get token for", username)

View File

@ -1,25 +1,14 @@
# shows artist info for a URN or URL # shows artist info for a URN or URL
import spotipy import spotipy
import sys from spotipy.oauth2 import SpotifyOAuth
import spotipy.util as util
if len(sys.argv) > 1: sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
username = sys.argv[1]
else:
print("Whoops, need your username!")
print("usage: python featured_playlists.py [username]")
sys.exit()
token = util.prompt_for_user_token(username) response = sp.featured_playlists()
print(response['message'])
if token: while response:
sp = spotipy.Spotify(auth=token)
response = sp.featured_playlists()
print(response['message'])
while response:
playlists = response['playlists'] playlists = response['playlists']
for i, item in enumerate(playlists['items']): for i, item in enumerate(playlists['items']):
print(playlists['offset'] + i, item['name']) print(playlists['offset'] + i, item['name'])
@ -28,5 +17,3 @@ if token:
response = sp.next(playlists) response = sp.next(playlists)
else: else:
response = None response = None
else:
print("Can't get token for", username)

View File

@ -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
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
scope = 'user-library-read' 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): def show_tracks(results):
for item in results['items']: for item in results['items']:
@ -19,14 +12,11 @@ def show_tracks(results):
print("%32.32s %s" % (track['artists'][0]['name'], track['name'])) 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: results = sp.current_user_saved_tracks()
sp = spotipy.Spotify(auth=token) show_tracks(results)
results = sp.current_user_saved_tracks()
show_tracks(results) while results['next']:
while results['next']:
results = sp.next(results) results = sp.next(results)
show_tracks(results) show_tracks(results)
else:
print("Can't get token for", username)

View File

@ -1,24 +1,13 @@
# shows artist info for a URN or URL # shows artist info for a URN or URL
import spotipy import spotipy
import sys from spotipy.oauth2 import SpotifyOAuth
import spotipy.util as util
if len(sys.argv) > 1: sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
username = sys.argv[1]
else:
print("Whoops, need your username!")
print("usage: python new_releases.py [username]")
sys.exit()
token = util.prompt_for_user_token(username) response = sp.new_releases()
if token: while response:
sp = spotipy.Spotify(auth=token)
response = sp.new_releases()
while response:
albums = response['albums'] albums = response['albums']
for i, item in enumerate(albums['items']): for i, item in enumerate(albums['items']):
print(albums['offset'] + i, item['name']) print(albums['offset'] + i, item['name'])
@ -27,5 +16,3 @@ if token:
response = sp.next(albums) response = sp.next(albums)
else: else:
response = None response = None
else:
print("Can't get token for", username)

11
examples/test.py Normal file
View File

@ -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'])

View File

@ -1,25 +1,10 @@
# 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
from spotipy.oauth2 import SpotifyOAuth
import spotipy.util as util sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
playlists = sp.current_user_playlists()
for playlist in playlists['items']:
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']) print(playlist['name'])
else:
print("Can't get token for", username)

View File

@ -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
import spotipy.util as util from spotipy.oauth2 import SpotifyOAuth
def show_tracks(results): def show_tracks(results):
@ -14,28 +13,21 @@ def show_tracks(results):
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) > 1: sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
username = sys.argv[1]
else:
print("Whoops, need your username!")
print("usage: python user_playlists_contents.py [username]")
sys.exit()
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']: for playlist in playlists['items']:
if playlist['owner']['id'] == username: if playlist['owner']['id'] == user_id:
print() print()
print(playlist['name']) print(playlist['name'])
print(' total tracks', playlist['tracks']['total']) print(' total tracks', playlist['tracks']['total'])
results = sp.playlist(playlist['id'], fields="tracks,next") results = sp.playlist(playlist['id'], fields="tracks,next")
tracks = results['tracks'] tracks = results['tracks']
show_tracks(tracks) show_tracks(tracks)
while tracks['next']: while tracks['next']:
tracks = sp.next(tracks) tracks = sp.next(tracks)
show_tracks(tracks) show_tracks(tracks)
else:
print("Can't get token for", username)

View File

@ -1,28 +1,12 @@
""" # Deletes user saved album
Deletes user saved album
"""
import sys
import spotipy 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()
scope = 'user-library-modify' scope = 'user-library-modify'
token = util.prompt_for_user_token(username, scope) sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
if token: uris = input("input a list of album URIs, URLs or IDs: ")
sp = spotipy.Spotify(auth=token) uris = list(map(str, uris.split()))
sp.trace = False deleted = sp.current_user_saved_albums_delete(uris)
uris = input("input a list of album URIs, URLs or IDs: ") print("Deletion successful.")
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)

View File

@ -6,6 +6,7 @@ __all__ = ["CLIENT_CREDS_ENV_VARS", "prompt_for_user_token"]
import logging import logging
import os import os
import warnings
import spotipy import spotipy
@ -29,6 +30,13 @@ def prompt_for_user_token(
oauth_manager=None, oauth_manager=None,
show_dialog=False 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 """ prompts the user to login if necessary and returns
the user token suitable for use with the spotipy.Spotify the user token suitable for use with the spotipy.Spotify
constructor constructor

View File

@ -264,7 +264,7 @@ class SpotipyUserApiTests(unittest.TestCase):
def test_current_user_top_artists(self): def test_current_user_top_artists(self):
response = self.spotify.current_user_top_artists() response = self.spotify.current_user_top_artists()
items = response['items'] items = response['items']
self.assertGreater(len(items), 0) self.assertGreaterEqual(len(items), 0)
class SpotipyBrowseApiTests(unittest.TestCase): class SpotipyBrowseApiTests(unittest.TestCase):