Sessions¶
-
class
spotify.Session(config=None)[source]¶ The Spotify session.
If no
configis provided, the default config is used.The session object will emit a number of events. See
SessionEventfor 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
Sessioninstance per process. This is a libspotify limitation. If you create a secondSessioninstance in the same process pyspotify will raise aRuntimeErrorwith the message “Session has already been initialized”.- Parameters
config (
ConfigorNone) – the session config
-
config= None¶ A
Configinstance with the current configuration.Once the session has been created, changing the attributes of this object will generally have no effect.
-
connection= None¶ An
Connectioninstance for controlling the connection to the Spotify servers.
A
Socialinstance 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:
usernameandpasswordusernameandblob
To get the
blobstring, you must once log in withusernameandpassword. You’ll then get theblobstring passed to thecredentials_blob_updatedcallback.If you set
remember_metoTrue, you can later login to the same account without providing anyusernameor credentials by callingrelogin().
-
logout()[source]¶ Log out the current user.
If you logged in with the
remember_meargument set toTrue, you will also need to callforget_me()to completely remove all credentials of the user that was logged in.
-
relogin()[source]¶ Relogin as the remembered user.
To be able do this, you must previously have logged in with
login()with theremember_meargument set toTrue.To check what user you’ll be logged in as if you call this method, see
remembered_user_name.
-
property
user_name¶ The username of the logged in user.
-
property
user_country¶ The country of the currently logged in user.
The
OFFLINE_STATUS_UPDATEDevent is emitted on the session object when this changes.
-
property
playlist_container¶ The
PlaylistContainerfor 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_offline_bitrate(bitrate, allow_resync=False)[source]¶ Set preferred
Bitratefor offline sync.If
allow_resyncisTruelibspotify may resynchronize already synced tracks.
-
property
volume_normalization¶ Whether volume normalization is active or not.
Set to
TrueorFalseto 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_THREADevent 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
EventLoopthat you can use for processing events when needed.
-
inbox_post_tracks(canonical_username, tracks, message, callback=None)[source]¶ Post a
messageand one or moretracksto the inbox of the user with the givencanonical_username.trackscan be a singleTrackor a list ofTrackobjects.Returns an
InboxPostResultthat can be used to check if the request completed successfully.If callback isn’t
None, it is called with anInboxPostResultinstance when the request has completed.
-
get_starred(canonical_username=None)[source]¶ Get the starred
Playlistfor the user withcanonical_username.If
canonical_usernameisn’t specified, the starred playlist for the currently logged in user is returned.
-
get_published_playlists(canonical_username=None)[source]¶ Get the
PlaylistContainerof published playlists for the user withcanonical_username.If
canonical_usernameisn’t specified, the published container for the currently logged in user is returned.
-
get_link(uri)[source]¶ Get
Linkfrom 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
Trackfrom 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
Trackfor 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.typewill beLinkType.LOCALTRACKfor the track’s link.Track.is_localwill beTruefor the track.
This method can be used to create local tracks that can be starred or added to playlists.
artistmay be an artist name.titlemay be a track name.albummay be an album name.lengthmay 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
Albumfrom 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
Artistfrom 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
Playlistfrom 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
Userfrom 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
Imagefrom a Spotify image URI.If
callbackisn’tNone, it is expected to be a callable that accepts a single argument, anImageinstance, 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.Warning
The search API was broken at 2016-02-03 by a server-side change made by Spotify. The functionality was never restored.
Please use the Spotify Web API to perform searches.
The
querystring can be free format, or use some prefixes liketitle:andartist: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
callbackisn’tNone, it is expected to be a callable that accepts a single argument, aSearchinstance, when the search completes.The
*_offsetand*_countarguments can be used to retrieve more search results. libspotify will currently not respect*_countvalues 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*_offsetvalues. See the*_totalattributes on theSearchto see how many results exists, and to figure out how many searches you’ll need to make to retrieve everything.search_typeis aSearchTypevalue. It defaults toSearchType.STANDARD.Returns a
Searchinstance.
-
get_toplist(type=None, region=None, canonical_username=None, callback=None)[source]¶ Get a
Toplistof artists, albums, or tracks that are the currently most popular worldwide or in a specific region.typeis aToplistTypeinstance that specifies the type of toplist to create.regionis either aToplistRegioninstance, or a 2-letter ISO 3166-1 country code as a unicode string, that specifies the geographical region to create a toplist for.If
regionisToplistRegion.USERandcanonical_usernameisn’t specified, the region of the current user will be used. Ifcanonical_usernameis specified, the region of the specified user will be used instead.If
callbackisn’tNone, it is expected to be a callable that accepts a single argument, aToplistinstance, 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 toon()Raises
AssertionErrorif there is none or multiple listeners forevent. 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 toon()
-
num_listeners(event=None)¶ Return the number of listeners for
event.Return the total number of listeners for all events on this object if
eventisNone.
-
off(event=None, listener=None)¶ Remove a
listenerthat was to be called onevent.If
listenerisNone, all listeners for the giveneventwill be removed.If
eventisNone, all listeners for all events on this object will be removed.
-
on(event, listener, *user_args)¶ Register a
listenerto be called onevent.The listener will be called with any extra arguments passed to
emit()first, and then the extra arguments passed toon()last.If the listener function returns
False, it is removed and will not be called the next time theeventis emitted.
-
class
spotify.SessionEvent[source]¶ Session events.
Using the
Sessionobject, 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= '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_UPDATEDevent.
-
LOGGED_OUT= 'logged_out'¶ Called when logout has completed or there is a permanent connection error.
- Parameters
session (
Session) – the current session
-
METADATA_UPDATED= '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= '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.OKerror when the problem is resolved.
-
MESSAGE_TO_USER= 'message_to_user'¶ Called when libspotify wants to show a message to the end user.
- Parameters
session (
Session) – the current sessiondata (text) – the message
-
NOTIFY_MAIN_THREAD= '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= '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 sessionaudio_format (
AudioFormat) – the audio formatframes (bytestring) – the audio frames
num_frames (int) – the number of frames
- Returns
the number of frames consumed
-
PLAY_TOKEN_LOST= '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= '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 sessiondata (text) – the message
-
END_OF_TRACK= 'end_of_track'¶ Called when all audio data for the current track has been delivered.
- Parameters
session (
Session) – the current session
-
STREAMING_ERROR= 'streaming_error'¶ Called when audio streaming cannot start or continue.
-
USER_INFO_UPDATED= 'user_info_updated'¶ Called when anything related to
Userobjects is updated.- Parameters
session (
Session) – the current session
-
START_PLAYBACK= 'start_playback'¶ Called when audio playback should start.
You need to implement a listener for the
GET_AUDIO_BUFFER_STATSevent for theSTART_PLAYBACKevent 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= 'stop_playback'¶ Called when audio playback should stop.
You need to implement a listener for the
GET_AUDIO_BUFFER_STATSevent for theSTOP_PLAYBACKevent 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= '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
AudioBufferStatsinstance
-
OFFLINE_STATUS_UPDATED= 'offline_status_updated'¶ Called when offline sync status is updated.
- Parameters
session (
Session) – the current session
-
CREDENTIALS_BLOB_UPDATED= 'credentials_blob_updated'¶ Called when storable credentials have been updated, typically right after login.
The
blobargument can be stored and later passed tologin()to login without storing the user’s password.- Parameters
session (
Session) – the current sessionblob (bytestring) – the authentication blob
-
CONNECTION_STATE_UPDATED= '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= 'scrobble_error'¶ Called when there is a scrobble error event.
-