mirror of
https://github.com/spotipy-dev/spotipy.git
synced 2026-10-12 01:10:45 +00:00
Sync branches (#920)
This commit is contained in:
1 parent
d7e8dd1e74
commit
4918305aba
33 files changed
+964
-366
No files matched your search
@@ -11,7 +11,7 @@ scope = 'playlist-modify-public'
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Adds track to user playlist')
|
||||
parser.add_argument('-t', '--tids', action='append',
|
||||
parser.add_argument('-u', '--uris', action='append',
|
||||
required=True, help='Track ids')
|
||||
parser.add_argument('-p', '--playlist', required=True,
|
||||
help='Playlist to add track to')
|
||||
@@ -22,7 +22,7 @@ def main():
|
||||
args = get_args()
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
sp.playlist_add_items(args.playlist, args.tids)
|
||||
sp.playlist_add_items(args.playlist, args.uris)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
+13
-27
@@ -13,7 +13,7 @@ Prerequisites
|
||||
export FLASK_ENV=development
|
||||
// so that you can invoke the app outside of the file's directory include
|
||||
export FLASK_APP=/path/to/spotipy/examples/app.py
|
||||
|
||||
|
||||
// on Windows, use `SET` instead of `export`
|
||||
|
||||
Run app.py
|
||||
@@ -27,7 +27,6 @@ import os
|
||||
from flask import Flask, session, request, redirect
|
||||
from flask_session import Session
|
||||
import spotipy
|
||||
import uuid
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = os.urandom(64)
|
||||
@@ -35,57 +34,44 @@ app.config['SESSION_TYPE'] = 'filesystem'
|
||||
app.config['SESSION_FILE_DIR'] = './.flask_session/'
|
||||
Session(app)
|
||||
|
||||
caches_folder = './.spotify_caches/'
|
||||
if not os.path.exists(caches_folder):
|
||||
os.makedirs(caches_folder)
|
||||
|
||||
def session_cache_path():
|
||||
return caches_folder + session.get('uuid')
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
if not session.get('uuid'):
|
||||
# Step 1. Visitor is unknown, give random ID
|
||||
session['uuid'] = str(uuid.uuid4())
|
||||
|
||||
cache_handler = spotipy.cache_handler.CacheFileHandler(cache_path=session_cache_path())
|
||||
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
|
||||
auth_manager = spotipy.oauth2.SpotifyOAuth(scope='user-read-currently-playing playlist-modify-private',
|
||||
cache_handler=cache_handler,
|
||||
show_dialog=True)
|
||||
cache_handler=cache_handler,
|
||||
show_dialog=True)
|
||||
|
||||
if request.args.get("code"):
|
||||
# Step 3. Being redirected from Spotify auth page
|
||||
# Step 2. Being redirected from Spotify auth page
|
||||
auth_manager.get_access_token(request.args.get("code"))
|
||||
return redirect('/')
|
||||
|
||||
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
||||
# Step 2. Display sign in link when no token
|
||||
# Step 1. Display sign in link when no token
|
||||
auth_url = auth_manager.get_authorize_url()
|
||||
return f'<h2><a href="{auth_url}">Sign in</a></h2>'
|
||||
|
||||
# Step 4. Signed in, display data
|
||||
# Step 3. Signed in, display data
|
||||
spotify = spotipy.Spotify(auth_manager=auth_manager)
|
||||
return f'<h2>Hi {spotify.me()["display_name"]}, ' \
|
||||
f'<small><a href="/sign_out">[sign out]<a/></small></h2>' \
|
||||
f'<a href="/playlists">my playlists</a> | ' \
|
||||
f'<a href="/currently_playing">currently playing</a> | ' \
|
||||
f'<a href="/current_user">me</a>' \
|
||||
f'<a href="/current_user">me</a>' \
|
||||
|
||||
|
||||
|
||||
@app.route('/sign_out')
|
||||
def sign_out():
|
||||
try:
|
||||
# Remove the CACHE file (.cache-test) so that a new user can authorize.
|
||||
os.remove(session_cache_path())
|
||||
session.clear()
|
||||
except OSError as e:
|
||||
print ("Error: %s - %s." % (e.filename, e.strerror))
|
||||
session.pop("token_info", None)
|
||||
return redirect('/')
|
||||
|
||||
|
||||
@app.route('/playlists')
|
||||
def playlists():
|
||||
cache_handler = spotipy.cache_handler.CacheFileHandler(cache_path=session_cache_path())
|
||||
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
|
||||
auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
|
||||
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
||||
return redirect('/')
|
||||
@@ -96,7 +82,7 @@ def playlists():
|
||||
|
||||
@app.route('/currently_playing')
|
||||
def currently_playing():
|
||||
cache_handler = spotipy.cache_handler.CacheFileHandler(cache_path=session_cache_path())
|
||||
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
|
||||
auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
|
||||
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
||||
return redirect('/')
|
||||
@@ -109,7 +95,7 @@ def currently_playing():
|
||||
|
||||
@app.route('/current_user')
|
||||
def current_user():
|
||||
cache_handler = spotipy.cache_handler.CacheFileHandler(cache_path=session_cache_path())
|
||||
cache_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
|
||||
auth_manager = spotipy.oauth2.SpotifyOAuth(cache_handler=cache_handler)
|
||||
if not auth_manager.validate_token(cache_handler.get_cached_token()):
|
||||
return redirect('/')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#Shows the list of all songs sung by the artist or the band
|
||||
# Shows the list of all songs sung by the artist or the band
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
@@ -34,7 +34,7 @@ def show_album_tracks(album):
|
||||
results = sp.next(results)
|
||||
tracks.extend(results['items'])
|
||||
for i, track in enumerate(tracks):
|
||||
logger.info('%s. %s', i+1, track['name'])
|
||||
logger.info('%s. %s', i + 1, track['name'])
|
||||
|
||||
|
||||
def show_artist_albums(artist):
|
||||
@@ -60,6 +60,7 @@ def show_artist(artist):
|
||||
if len(artist['genres']) > 0:
|
||||
logger.info('Genres: %s', ','.join(artist['genres']))
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
artist = get_artist(args.artist)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import argparse
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Follows a playlist based on playlist ID')
|
||||
parser.add_argument('-p', '--playlist', required=True, help='Playlist ID')
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
|
||||
if args.playlist is None:
|
||||
# Uses the Spotify Global Top 50 playlist
|
||||
spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(
|
||||
'37i9dQZEVXbMDoHDwVN2tF')
|
||||
|
||||
else:
|
||||
spotipy.Spotify(auth_manager=SpotifyOAuth()).current_user_follow_playlist(args.playlist)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -5,4 +5,4 @@ from spotipy.oauth2 import SpotifyOAuth
|
||||
# set open_browser=False to prevent Spotipy from attempting to open the default browser
|
||||
spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(open_browser=False))
|
||||
|
||||
print(spotify.me())
|
||||
print(spotify.me())
|
||||
@@ -8,4 +8,4 @@ sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
|
||||
|
||||
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']))
|
||||
@@ -13,4 +13,4 @@ for sp_range in ranges:
|
||||
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()
|
||||
print()
|
||||
@@ -0,0 +1,12 @@
|
||||
# Add a list of items (URI) to a playlist (URI)
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="YOUR_APP_CLIENT_ID",
|
||||
client_secret="YOUR_APP_CLIENT_SECRET",
|
||||
redirect_uri="YOUR_APP_REDIRECT_URI",
|
||||
scope="playlist-modify-private"
|
||||
))
|
||||
|
||||
sp.playlist_add_items('playlist_id', ['list_of_items'])
|
||||
@@ -12,10 +12,10 @@ while True:
|
||||
offset=offset,
|
||||
fields='items.track.id,total',
|
||||
additional_types=['track'])
|
||||
|
||||
|
||||
if len(response['items']) == 0:
|
||||
break
|
||||
|
||||
|
||||
pprint(response['items'])
|
||||
offset = offset + len(response['items'])
|
||||
print(offset, "/", response['total'])
|
||||
@@ -1,4 +1,5 @@
|
||||
# shows artist info for a URN or URL
|
||||
# scope is not required for this function
|
||||
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
import spotipy
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Shows all artists featured on an album
|
||||
|
||||
# usage: featured_artists.py spotify:album:[album urn]
|
||||
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
import sys
|
||||
import spotipy
|
||||
from pprint import pprint
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
urn = sys.argv[1]
|
||||
else:
|
||||
urn = 'spotify:album:5yTx83u3qerZF7GRJu7eFk'
|
||||
|
||||
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
|
||||
album = sp.album(urn)
|
||||
|
||||
featured_artists = set()
|
||||
|
||||
items = album['tracks']['items']
|
||||
|
||||
for item in items:
|
||||
for ele in item['artists']:
|
||||
if 'name' in ele:
|
||||
featured_artists.add(ele['name'])
|
||||
|
||||
pprint(featured_artists)
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
#Shows the name of the artist/band and their image by giving a link
|
||||
# Shows the name of the artist/band and their image by giving a link
|
||||
import sys
|
||||
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import spotipy
|
||||
from spotipy.oauth2 import SpotifyOAuth
|
||||
|
||||
logger = logging.getLogger('examples.unfollow_playlist')
|
||||
logging.basicConfig(level='DEBUG')
|
||||
|
||||
'''
|
||||
Spotify doesn't have a dedicated endpoint for deleting a playlist. However,
|
||||
unfollowing a playlist has the effect of deleting it from the user's account.
|
||||
When a playlist is removed from the user's account, the system unfollows it,
|
||||
and then no longer shows it in playlist list.'''
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser(description='Unfollows a playlist')
|
||||
parser.add_argument('-p', '--playlist', required=True,
|
||||
help='Playlist id')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = get_args()
|
||||
sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
|
||||
sp.current_user_unfollow_playlist(args.playlist)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -16,4 +16,4 @@ sp = spotipy.Spotify(auth_manager=SpotifyOAuth())
|
||||
playlists = sp.user_playlists(username)
|
||||
|
||||
for playlist in playlists['items']:
|
||||
print(playlist['name'])
|
||||
print(playlist['name'])
|
||||
Reference in new issue
Block a user