Deprecate util.prompt_for_user_token()

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

No files matched your search

+38 -143
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]*).
@@ -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=<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