Sessions

class spotify.Session(config=None)[source]

The Spotify session.

If no config is provided, the default config is used.

The session object will emit a number of events. See SessionEvent for a list of all available events and how to connect your own listener functions up to get called when the events happens.

Warning

You can only have one Session instance per process. This is a libspotify limitation. If you create a second Session instance in the same process pyspotify will raise a RuntimeError with the message “Session has already been initialized”.

Parameters:config (Config or None) – the session config
config = None

A Config instance with the current configuration.

Once the session has been created, changing the attributes of this object will generally have no effect.

connection = None

An Connection instance for controlling the connection to the Spotify servers.

offline = None

An Offline instance for controlling offline sync.

player = None

A Player instance for controlling playback.

social = None

A Social instance for controlling social sharing.

login(username, password=None, remember_me=False, blob=None)[source]

Authenticate to Spotify’s servers.

You can login with one of two combinations:

  • username and password
  • username and blob

To get the blob string, you must once log in with username and password. You’ll then get the blob string passed to the credentials_blob_updated callback.

If you set remember_me to True, you can later login to the same account without providing any username or credentials by calling relogin().

logout()[source]

Log out the current user.

If you logged in with the remember_me argument set to True, you will also need to call forget_me() to completely remove all credentials of the user that was logged in.

remembered_user_name

The username of the remembered user from a previous login() call.

relogin()[source]

Relogin as the remembered user.

To be able do this, you must previously have logged in with login() with the remember_me argument set to True.

To check what user you’ll be logged in as if you call this method, see remembered_user_name.

forget_me()[source]

Forget the remembered user from a previous login() call.

user

The logged in User.

user_name

The username of the logged in user.

user_country

The country of the currently logged in user.

The OFFLINE_STATUS_UPDATED event is emitted on the session object when this changes.

playlist_container

The PlaylistContainer for the currently logged in user.

inbox

The inbox Playlist for the currently logged in user.

set_cache_size(size)[source]

Set maximum size in MB for libspotify’s cache.

If set to 0 (the default), up to 10% of the free disk space will be used.

flush_caches()[source]

Write all cached data to disk.

libspotify does this regularly and on logout, so you should never need to call this method yourself.

preferred_bitrate(bitrate)[source]

Set preferred Bitrate for music streaming.

preferred_offline_bitrate(bitrate, allow_resync=False)[source]

Set preferred Bitrate for offline sync.

If allow_resync is True libspotify may resynchronize already synced tracks.

volume_normalization

Whether volume normalization is active or not.

Set to True or False to change.

process_events()[source]

Process pending events in libspotify.

This method must be called for most callbacks to be called. Without calling this method, you’ll only get the callbacks that are called from internal libspotify threads. When the NOTIFY_MAIN_THREAD event is emitted (from an internal libspotify thread), it’s your job to make sure this method is called (from the thread you use for accessing Spotify), so that further callbacks can be triggered (from the same thread).

pyspotify provides an EventLoop that you can use for processing events when needed.

inbox_post_tracks(canonical_username, tracks, message, callback=None)[source]

Post a message and one or more tracks to the inbox of the user with the given canonical_username.

tracks can be a single Track or a list of Track objects.

Returns an InboxPostResult that can be used to check if the request completed successfully.

If callback isn’t None, it is called with an InboxPostResult instance when the request has completed.

get_starred(canonical_username=None)[source]

Get the starred Playlist for the user with canonical_username.

If canonical_username isn’t specified, the starred playlist for the currently logged in user is returned.

get_published_playlists(canonical_username=None)[source]

Get the PlaylistContainer of published playlists for the user with canonical_username.

If canonical_username isn’t specified, the published container for the currently logged in user is returned.

Get Link from any Spotify URI.

A link can be created from a string containing a Spotify URI on the form spotify:....

Example:

>>> session = spotify.Session()
# ...
>>> session.get_link(
...     'spotify:track:2Foc5Q5nqNiosCNqttzHof')
Link('spotify:track:2Foc5Q5nqNiosCNqttzHof')
>>> session.get_link(
...     'http://open.spotify.com/track/4wl1dK5dHGp3Ig51stvxb0')
Link('spotify:track:4wl1dK5dHGp3Ig51stvxb0')
get_track(uri)[source]

Get Track from a Spotify track URI.

Example:

>>> session = spotify.Session()
# ...
>>> track = session.get_track(
...     'spotify:track:2Foc5Q5nqNiosCNqttzHof')
>>> track.load().name
u'Get Lucky'
get_local_track(artist=None, title=None, album=None, length=None)[source]

Get Track for a local track.

Spotify’s official clients supports adding your local music files to Spotify so they can be played in the Spotify client. These are not synced with Spotify’s servers or between your devices and there is not trace of them in your Spotify user account. The exception is when you add one of these local tracks to a playlist or mark them as starred. This creates a “local track” which pyspotify also will be able to observe.

“Local tracks” can be recognized in several ways:

  • The track’s URI will be of the form spotify:local:ARTIST:ALBUM:TITLE:LENGTH_IN_SECONDS. Any of the parts in all caps can be left out if there is no information available. That is, spotify:local:::: is a valid local track URI.
  • Link.type will be LinkType.LOCALTRACK for the track’s link.
  • Track.is_local will be True for the track.

This method can be used to create local tracks that can be starred or added to playlists.

artist may be an artist name. title may be a track name. album may be an album name. length may be a track length in milliseconds.

Note that when creating a local track you provide the length in milliseconds, while the local track URI contains the length in seconds.

get_album(uri)[source]

Get Album from a Spotify album URI.

Example:

>>> session = spotify.Session()
# ...
>>> album = session.get_album(
...     'spotify:album:6wXDbHLesy6zWqQawAa91d')
>>> album.load().name
u'Forward / Return'
get_artist(uri)[source]

Get Artist from a Spotify artist URI.

Example:

>>> session = spotify.Session()
# ...
>>> artist = session.get_artist(
...     'spotify:artist:22xRIphSN7IkPVbErICu7s')
>>> artist.load().name
u'Rob Dougan'
get_playlist(uri)[source]

Get Playlist from a Spotify playlist URI.

Example:

>>> session = spotify.Session()
# ...
>>> playlist = session.get_playlist(
...     'spotify:user:fiat500c:playlist:54k50VZdvtnIPt4d8RBCmZ')
>>> playlist.load().name
u'500C feelgood playlist'
get_user(uri)[source]

Get User from a Spotify user URI.

Example:

>>> session = spotify.Session()
# ...
>>> user = session.get_user('spotify:user:jodal')
>>> user.load().display_name
u'jodal'
get_image(uri, callback=None)[source]

Get Image from a Spotify image URI.

If callback isn’t None, it is expected to be a callable that accepts a single argument, an Image instance, when the image is done loading.

Example:

>>> session = spotify.Session()
# ...
>>> image = session.get_image(
...     'spotify:image:a0bdcbe11b5cd126968e519b5ed1050b0e8183d0')
>>> image.load().data_uri[:50]
u'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD'
search(query, callback=None, track_offset=0, track_count=20, album_offset=0, album_count=20, artist_offset=0, artist_count=20, playlist_offset=0, playlist_count=20, search_type=None)[source]

Search Spotify for tracks, albums, artists, and playlists matching query.

The query string can be free format, or use some prefixes like title: and artist: to limit what to match on. There is no official docs on the search query format, but there’s a Spotify blog post from 2008 with some examples.

If callback isn’t None, it is expected to be a callable that accepts a single argument, a Search instance, when the search completes.

The *_offset and *_count arguments can be used to retrieve more search results. libspotify will currently not respect *_count values higher than 200, though this may change at any time as the limit isn’t documented in any official docs. If you want to retrieve more than 200 results, you’ll have to search multiple times with different *_offset values. See the *_total attributes on the Search to see how many results exists, and to figure out how many searches you’ll need to make to retrieve everything.

search_type is a SearchType value. It defaults to SearchType.STANDARD.

Returns a Search instance.

get_toplist(type=None, region=None, canonical_username=None, callback=None)[source]

Get a Toplist of artists, albums, or tracks that are the currently most popular worldwide or in a specific region.

type is a ToplistType instance that specifies the type of toplist to create.

region is either a ToplistRegion instance, or a 2-letter ISO 3166-1 country code as a unicode string, that specifies the geographical region to create a toplist for.

If region is ToplistRegion.USER and canonical_username isn’t specified, the region of the current user will be used. If canonical_username is specified, the region of the specified user will be used instead.

If callback isn’t None, it is expected to be a callable that accepts a single argument, a Toplist instance, when the toplist request completes.

Example:

>>> import spotify
>>> session = spotify.Session()
# ...
>>> toplist = session.get_toplist(
...     type=spotify.ToplistType.TRACKS, region='US')
>>> toplist.load()
>>> len(toplist.tracks)
100
>>> len(toplist.artists)
0
>>> toplist.tracks[0]
Track(u'spotify:track:2dLLR6qlu5UJ5gk0dKz0h3')
call(event, *event_args)

Call the single registered listener for event.

The listener will be called with any extra arguments passed to call() first, and then the extra arguments passed to on()

Raises AssertionError if there is none or multiple listeners for event. Returns the listener’s return value on success.

emit(event, *event_args)

Call the registered listeners for event.

The listeners will be called with any extra arguments passed to emit() first, and then the extra arguments passed to on()

num_listeners(event=None)

Return the number of listeners for event.

Return the total number of listeners for all events on this object if event is None.

off(event=None, listener=None)

Remove a listener that was to be called on event.

If listener is None, all listeners for the given event will be removed.

If event is None, all listeners for all events on this object will be removed.

on(event, listener, *user_args)

Register a listener to be called on event.

The listener will be called with any extra arguments passed to emit() first, and then the extra arguments passed to on() last.

If the listener function returns False, it is removed and will not be called the next time the event is emitted.

class spotify.SessionEvent[source]

Session events.

Using the Session object, you can register listener functions to be called when various session related events occurs. This class enumerates the available events and the arguments your listener functions will be called with.

Example usage:

import spotify

def logged_in(session, error_type):
    if error_type is spotify.ErrorType.OK:
        print('Logged in as %s' % session.user)
    else:
        print('Login failed: %s' % error_type)

session = spotify.Session()
session.on(spotify.SessionEvent.LOGGED_IN, logged_in)
session.login('alice', 's3cret')

All events will cause debug log statements to be emitted, even if no listeners are registered. Thus, there is no need to register listener functions just to log that they’re called.

LOGGED_IN = u'logged_in'

Called when login has completed.

Note that even if login has succeeded, that does not mean that you’re online yet as libspotify may have cached enough information to let you authenticate with Spotify while offline.

This event should be used to get notified about login errors. To get notified about the authentication and connection state, refer to the SessionEvent.CONNECTION_STATE_UPDATED event.

Parameters:
  • session (Session) – the current session
  • error_type (ErrorType) – the login error type
LOGGED_OUT = u'logged_out'

Called when logout has completed or there is a permanent connection error.

Parameters:session (Session) – the current session
METADATA_UPDATED = u'metadata_updated'

Called when some metadata has been updated.

There is no way to know what metadata was updated, so you’ll have to refresh all you metadata caches.

Parameters:session (Session) – the current session
CONNECTION_ERROR = u'connection_error'

Called when there is a connection error and libspotify has problems reconnecting to the Spotify service.

May be called repeatedly as long as the problem persists. Will be called with an ErrorType.OK error when the problem is resolved.

Parameters:
  • session (Session) – the current session
  • error_type (ErrorType) – the connection error type
MESSAGE_TO_USER = u'message_to_user'

Called when libspotify wants to show a message to the end user.

Parameters:
  • session (Session) – the current session
  • data (text) – the message
NOTIFY_MAIN_THREAD = u'notify_main_thread'

Called when processing on the main thread is needed.

When this is called, you should call process_events() from your main thread. Failure to do so may cause request timeouts, or a lost connection.

Warning

This event is emitted from an internal libspotify thread. Thus, your event listener must not block, and must use proper synchronization around anything it does.

Parameters:session (Session) – the current session
MUSIC_DELIVERY = u'music_delivery'

Called when there is decompressed audio data available.

If the function returns a lower number of frames consumed than num_frames, libspotify will retry delivery of the unconsumed frames in about 100ms. This can be used for rate limiting if libspotify is giving you audio data too fast.

Note

You can register at most one event listener for this event.

Warning

This event is emitted from an internal libspotify thread. Thus, your event listener must not block, and must use proper synchronization around anything it does.

Parameters:
  • session (Session) – the current session
  • audio_format (AudioFormat) – the audio format
  • frames (bytestring) – the audio frames
  • num_frames (int) – the number of frames
Returns:

the number of frames consumed

PLAY_TOKEN_LOST = u'play_token_lost'

Music has been paused because an account only allows music to be played from one location simultaneously.

When this event is emitted, you should pause playback.

Parameters:session (Session) – the current session
LOG_MESSAGE = u'log_message'

Called when libspotify have something to log.

Note that pyspotify logs this for you, so you’ll probably never need to register a listener for this event.

Parameters:
  • session (Session) – the current session
  • data (text) – the message
END_OF_TRACK = u'end_of_track'

Called when all audio data for the current track has been delivered.

Parameters:session (Session) – the current session
STREAMING_ERROR = u'streaming_error'

Called when audio streaming cannot start or continue.

Parameters:
  • session (Session) – the current session
  • error_type (ErrorType) – the streaming error type
USER_INFO_UPDATED = u'user_info_updated'

Called when anything related to User objects is updated.

Parameters:session (Session) – the current session
START_PLAYBACK = u'start_playback'

Called when audio playback should start.

You need to implement a listener for the GET_AUDIO_BUFFER_STATS event for the START_PLAYBACK event to be useful.

Warning

This event is emitted from an internal libspotify thread. Thus, your event listener must not block, and must use proper synchronization around anything it does.

Parameters:session (Session) – the current session
STOP_PLAYBACK = u'stop_playback'

Called when audio playback should stop.

You need to implement a listener for the GET_AUDIO_BUFFER_STATS event for the STOP_PLAYBACK event to be useful.

Warning

This event is emitted from an internal libspotify thread. Thus, your event listener must not block, and must use proper synchronization around anything it does.

Parameters:session (Session) – the current session
GET_AUDIO_BUFFER_STATS = u'get_audio_buffer_stats'

Called to query the application about its audio buffer.

Note

You can register at most one event listener for this event.

Warning

This event is emitted from an internal libspotify thread. Thus, your event listener must not block, and must use proper synchronization around anything it does.

Parameters:session (Session) – the current session
Returns:an AudioBufferStats instance
OFFLINE_STATUS_UPDATED = u'offline_status_updated'

Called when offline sync status is updated.

Parameters:session (Session) – the current session
CREDENTIALS_BLOB_UPDATED = u'credentials_blob_updated'

Called when storable credentials have been updated, typically right after login.

The blob argument can be stored and later passed to login() to login without storing the user’s password.

Parameters:
  • session (Session) – the current session
  • blob (bytestring) – the authentication blob
CONNECTION_STATE_UPDATED = u'connection_state_updated'

Called when the connection state is updated.

The connection state includes login, logout, offline mode, etc.

Parameters:session (Session) – the current session
SCROBBLE_ERROR = u'scrobble_error'

Called when there is a scrobble error event.

Parameters:
  • session (Session) – the current session
  • error_type (ErrorType) – the scrobble error type
PRIVATE_SESSION_MODE_CHANGED = u'private_session_mode_changed'

Called when there is a change in the private session mode.

Parameters:
  • session (Session) – the current session
  • is_private (bool) – whether the session is private