Doc improvements for readthedocs

This commit is contained in:
Paul Lamere 2014-08-22 11:48:12 -04:00
parent 99f417088e
commit b455d529f0
4 changed files with 128 additions and 19 deletions

View File

@ -1,7 +1,7 @@
.. image:: images/spotify-web-api-doc.jpg .. image:: images/spotify-web-api-doc.jpg
:width: 100 % :width: 100 %
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*
@ -23,7 +23,6 @@ released by the artist 'Birdy'::
for album in albums: for album in albums:
print(album['name']) print(album['name'])
print album
Here's another example showing how to get 30 second samples and cover art Here's another example showing how to get 30 second samples and cover art
for the top 10 tracks for Led Zeppelin:: for the top 10 tracks for Led Zeppelin::
@ -163,6 +162,87 @@ IDs URIs and URLs
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
--------
Here are a few more examples of using *Spotipy*.
Add tracks to a playlist::
import pprint
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(results):
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.user_playlist(username, 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
API Reference API Reference
============== ==============
@ -193,12 +273,38 @@ API Reference
Support Support
======= =======
You can ask questions about Spotipy on Stack Overflow. Dont forget to add the
*Spotipy* tag, and any other relevant tags as well, before posting.
http://stackoverflow.com/questions/ask
If you think you've found a bug, let us know at
`Spotify Issues <https://github.com/plamere/spotipy/issues>`_
Contribute Contribute
========== ==========
Spotipy authored by Paul Lamere (plamere) with contributions by:
- Daniel Beaudry // danbeaudry
- Faruk Emre Sahin // fsahin
- George // rogueleaderr
- Henry Greville // sethaurus
- Hugo // hugovk
- José Manuel Pérez // JMPerez
- Lucas Nunno // lnunno
- Lynn Root // econchick
- Matt Dennewitz // mattdennewitz
- Matthew Duck // mattduck
- Michael Thelin // thelinmichael
- Ryan Choi // ryankicks
- Simon Metson // drsm79
- Tim Balzer // timbalzer
- corycorycory // corycorycory
License License
======= =======
https://github.com/plamere/spotipy/blob/master/LICENSE.txt
Indices and tables Indices and tables

View File

@ -5,7 +5,6 @@ import pprint
import sys import sys
import spotipy import spotipy
import spotipy.oauth2 as oauth2
import spotipy.util as util import spotipy.util as util
if len(sys.argv) > 3: if len(sys.argv) > 3:
@ -23,6 +22,6 @@ if token:
sp = spotipy.Spotify(auth=token) sp = spotipy.Spotify(auth=token)
sp.trace = False sp.trace = False
results = sp.user_playlist_add_tracks(username, playlist_id, track_ids) results = sp.user_playlist_add_tracks(username, playlist_id, track_ids)
pprint.pprint(results) print results
else: else:
print "Can't get token for", username print "Can't get token for", username

View File

@ -1,15 +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 pprint
import sys import sys
import os import os
import subprocess
import spotipy import spotipy
import spotipy.oauth2 as oauth2
import spotipy.util as util import spotipy.util as util
def show_tracks(results): def show_tracks(results):
for i, item in enumerate(tracks['items']): for i, item in enumerate(tracks['items']):
track = item['track'] track = item['track']
@ -30,8 +25,6 @@ if __name__ == '__main__':
top = 40 top = 40
sp = spotipy.Spotify(auth=token) sp = spotipy.Spotify(auth=token)
playlists = sp.user_playlists(username) playlists = sp.user_playlists(username)
# pprint.pprint(playlists)
matches = 0
for playlist in playlists['items']: for playlist in playlists['items']:
if playlist['owner']['id'] == username: if playlist['owner']['id'] == username:
print print
@ -39,15 +32,10 @@ if __name__ == '__main__':
print ' total tracks', playlist['tracks']['total'] print ' total tracks', playlist['tracks']['total']
results = sp.user_playlist(username, playlist['id'], fields="tracks,next") results = sp.user_playlist(username, playlist['id'], fields="tracks,next")
tracks = results['tracks'] tracks = results['tracks']
# pprint.pprint(results)
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)
# pprint.pprint(results)
matches += 1
if matches >= top:
break
else: else:
print "Can't get token for", username print "Can't get token for", username

View File

@ -13,7 +13,6 @@ class SpotifyOauthError(Exception):
class SpotifyOAuth(object): class SpotifyOAuth(object):
''' '''
Implements Authorization Code Flow for Spotify's OAuth implementation. Implements Authorization Code Flow for Spotify's OAuth implementation.
Docs: https://developer.spotify.com/spotify-web-api/authorization-guide/#authorization_code_flow
''' '''
OAUTH_AUTHORIZE_URL = 'https://accounts.spotify.com/authorize' OAUTH_AUTHORIZE_URL = 'https://accounts.spotify.com/authorize'
@ -32,6 +31,7 @@ class SpotifyOAuth(object):
- scope - the desired scope of the request - scope - the desired scope of the request
- cache_path - path to location to save tokens - cache_path - path to location to save tokens
''' '''
self.client_id = client_id self.client_id = client_id
self.client_secret = client_secret self.client_secret = client_secret
self.redirect_uri = redirect_uri self.redirect_uri = redirect_uri
@ -40,6 +40,8 @@ class SpotifyOAuth(object):
self.scope=self._normalize_scope(scope) self.scope=self._normalize_scope(scope)
def get_cached_token(self): def get_cached_token(self):
''' Gets a cached auth token
'''
token_info = None token_info = None
if self.cache_path: if self.cache_path:
try: try:
@ -75,6 +77,8 @@ class SpotifyOAuth(object):
return token_info['expires_at'] < now return token_info['expires_at'] < now
def get_authorize_url(self): def get_authorize_url(self):
""" Gets the URL to use to authorize this app
"""
payload = {'client_id': self.client_id, payload = {'client_id': self.client_id,
'response_type': 'code', 'response_type': 'code',
'redirect_uri': self.redirect_uri} 'redirect_uri': self.redirect_uri}
@ -87,13 +91,25 @@ class SpotifyOAuth(object):
return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams) return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams)
def parse_response_code(self, response): def parse_response_code(self, url):
""" Parse the response code in the given response url
Parameters:
- url - the response url
"""
try: try:
return response.split("?code=")[1].split("&")[0] return url.split("?code=")[1].split("&")[0]
except IndexError: except IndexError:
return None return None
def get_access_token(self, code): def get_access_token(self, code):
""" Gets the access token for the app given the code
Parameters:
- code - the response code
"""
payload = {'redirect_uri': self.redirect_uri, payload = {'redirect_uri': self.redirect_uri,
'code': code, 'code': code,
'grant_type': 'authorization_code'} 'grant_type': 'authorization_code'}