Search code examples
pythonpython-2.7spotifylibspotify

Loading Spotify album metadatas with PySpotify


I can't figure how to load album metadatas with pyspotify. Whatever I've tried, albumbrowser is still loading.

Here is my class :

logged_in is called by a callback when we are successfully logged in using session.connect() in main function.

class sessionManager(SpotifySessionManager):
    appkey_file =  os.path.join(os.path.dirname(__file__), 'spotify_appkey.key')

    def __init__(self, *a, **kw):
            SpotifySessionManager.__init__(self, *a, **kw)


    def logged_in(self, session, error):
            link=Link.from_string("spotify:album:4DR0GWo7w2GJyQnFVa4jAB")
            line=""
            if link.type() == link.LINK_ALBUM:
                    browser = AlbumBrowser(link.as_album())
                    while not browser.is_loaded():
                            line+="."
                            time.sleep(1)
                            sys.stdout.write("\r%s" % line)
                            sys.stdout.flush()
                    for track in browser:
                            print track.name()
            if link.type() == link.LINK_ARTIST:
                    browser = ArtistBrowser(link.as_artist())
                    while not browser.is_loaded():
                            line+="."
                            time.sleep(1)
                            sys.stdout.write("\r%s" % line)
                            sys.stdout.flush()
                    for album in browser:
                            print album.name()

Here is how my class in invoked :

if __name__ == '__main__':
        import optparse
        op = optparse.OptionParser(version="%prog 0.1")
        op.add_option("-u", "--username", help="Spotify username")
        op.add_option("-p", "--password", help="Spotify password")
        op.add_option("-v", "--verbose", help="Show debug information",
                dest="verbose", action="store_true")
        op.add_option("-b", "--album", help="Spotify Album ID")
        (options, args) = op.parse_args()
        if options.verbose:
                logging.basicConfig(level=logging.DEBUG)
        sessionM = sessionManager(options.username, options.password, True)
        sessionM.connect()

Do you have an idea about something I would forget?


Solution

  • Your problem is likely this:

    while not browser.is_loaded():
    

    libSpotify (and, by extension, PySpotify) runs in the thread you initialise it on. Since you're doing a tight loop, you're actually blocking libSpotify's ability to do anything, and the browse request will eventually time out.

    Instead of doing a tight loops, rely on callbacks to be notified when stuff has loaded.