Skip to content

Commit

Permalink
Doc improvements for readthedocs
Browse files Browse the repository at this point in the history
  • Loading branch information
plamere committed Aug 22, 2014
1 parent 99f4170 commit b455d52
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 19 deletions.
110 changes: 108 additions & 2 deletions docs/index.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
.. image:: images/spotify-web-api-doc.jpg
:width: 100 %

Spotipy
Welcome to Spotipy!
===================================
*Spotipy* is a lightweight Python library for the `Spotify Web API
<https://developer.spotify.com/web-api/>`_. With *Spotipy*
Expand All @@ -23,7 +23,6 @@ released by the artist 'Birdy'::

for album in albums:
print(album['name'])
print album

Here's another example showing how to get 30 second samples and cover art
for the top 10 tracks for Led Zeppelin::
Expand Down Expand Up @@ -163,6 +162,87 @@ IDs URIs and URLs
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*.

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

Expand Down Expand Up @@ -193,12 +273,38 @@ API Reference

Support
=======
You can ask questions about Spotipy on Stack Overflow. Don’t 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
==========
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
=======
https://github.com/plamere/spotipy/blob/master/LICENSE.txt


Indices and tables
Expand Down
3 changes: 1 addition & 2 deletions examples/add_tracks_to_playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import sys

import spotipy
import spotipy.oauth2 as oauth2
import spotipy.util as util

if len(sys.argv) > 3:
Expand All @@ -23,6 +22,6 @@
sp = spotipy.Spotify(auth=token)
sp.trace = False
results = sp.user_playlist_add_tracks(username, playlist_id, track_ids)
pprint.pprint(results)
print results
else:
print "Can't get token for", username
12 changes: 0 additions & 12 deletions examples/user_playlists_contents.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
# shows a user's playlists (need to be authenticated via oauth)

import pprint
import sys
import os
import subprocess

import spotipy
import spotipy.oauth2 as oauth2
import spotipy.util as util


def show_tracks(results):
for i, item in enumerate(tracks['items']):
track = item['track']
Expand All @@ -30,24 +25,17 @@ def show_tracks(results):
top = 40
sp = spotipy.Spotify(auth=token)
playlists = sp.user_playlists(username)
# pprint.pprint(playlists)
matches = 0
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']
# pprint.pprint(results)
show_tracks(tracks)
while tracks['next']:
tracks = sp.next(tracks)
show_tracks(tracks)
# pprint.pprint(results)
matches += 1
if matches >= top:
break
else:
print "Can't get token for", username

22 changes: 19 additions & 3 deletions spotipy/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ class SpotifyOauthError(Exception):
class SpotifyOAuth(object):
'''
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'
Expand All @@ -32,6 +31,7 @@ def __init__(self, client_id, client_secret, redirect_uri,
- scope - the desired scope of the request
- cache_path - path to location to save tokens
'''

self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
Expand All @@ -40,6 +40,8 @@ def __init__(self, client_id, client_secret, redirect_uri,
self.scope=self._normalize_scope(scope)

def get_cached_token(self):
''' Gets a cached auth token
'''
token_info = None
if self.cache_path:
try:
Expand Down Expand Up @@ -75,6 +77,8 @@ def _is_token_expired(self, token_info):
return token_info['expires_at'] < now

def get_authorize_url(self):
""" Gets the URL to use to authorize this app
"""
payload = {'client_id': self.client_id,
'response_type': 'code',
'redirect_uri': self.redirect_uri}
Expand All @@ -87,13 +91,25 @@ def get_authorize_url(self):

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:
return response.split("?code=")[1].split("&")[0]
return url.split("?code=")[1].split("&")[0]
except IndexError:
return None

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,
'code': code,
'grant_type': 'authorization_code'}
Expand Down

0 comments on commit b455d52

Please sign in to comment.