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

2
FAQ.md
View File

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

View File

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

View File

@ -3,6 +3,7 @@
Welcome to Spotipy!
===================================
*Spotipy* is a lightweight Python library for the `Spotify Web API
<https://developer.spotify.com/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 <https://developer.spotify.com/web-api/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 <https://developer.spotify.com/dashboard/applications>`_
(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)
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
=======================
@ -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 <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
==========
Spotipy authored by Paul Lamere (plamere) with contributions by:
- Daniel Beaudry // danbeaudry

View File

@ -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 = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
sp.current_user_saved_albums_add(albums=args.aids)
else:
logger.error("Can't get token for %s", args.username)
if __name__ == '__main__':

View File

@ -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)
if __name__ == '__main__':

View File

@ -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__':

View File

@ -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 = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
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,
collaborative=args.collaborative or args.independent,
description=args.description)
else:
logger.error("Can't get token for %s", args.username)
if __name__ == '__main__':

View File

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

View File

@ -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__':

View File

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

View File

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

View File

@ -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']
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']):
print(i, item['name'])
print()
else:
print("Can't get token for", username)

View File

@ -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)
ranges = ['short_term', 'medium_term', 'long_term']
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()
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 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)

View File

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

View File

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

View File

@ -1,25 +1,14 @@
# 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)
response = sp.featured_playlists()
print(response['message'])
while response:
while response:
playlists = response['playlists']
for i, item in enumerate(playlists['items']):
print(playlists['offset'] + i, item['name'])
@ -28,5 +17,3 @@ if token:
response = sp.next(playlists)
else:
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.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()
show_tracks(results)
while results['next']:
results = sp.current_user_saved_tracks()
show_tracks(results)
while results['next']:
results = sp.next(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
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)
response = sp.new_releases()
while response:
while response:
albums = response['albums']
for i, item in enumerate(albums['items']):
print(albums['offset'] + i, item['name'])
@ -27,5 +16,3 @@ if token:
response = sp.next(albums)
else:
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)
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']:
for playlist in playlists['items']:
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.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:
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)
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.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.")

View File

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

View File

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