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 secondSession
instance in the same process pyspotify will raise aRuntimeError
with the message “Session has already been initialized”.Parameters: config ( Config
orNone
) – 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.
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
andpassword
username
andblob
To get the
blob
string, you must once log in withusername
andpassword
. You’ll then get theblob
string passed to thecredentials_blob_updated
callback.If you set
remember_me
toTrue
, you can later login to the same account without providing anyusername
or credentials by callingrelogin()
.
-
logout
()[source]¶ Log out the current user.
If you logged in with the
remember_me
argument 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_me
argument set toTrue
.To check what user you’ll be logged in as if you call this method, see
remembered_user_name
.
-
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.
-
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
Bitrate
for offline sync.If
allow_resync
isTrue
libspotify may resynchronize already synced tracks.
-
volume_normalization
¶ Whether volume normalization is active or not.
Set to
True
orFalse
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 moretracks
to the inbox of the user with the givencanonical_username
.tracks
can be a singleTrack
or a list ofTrack
objects.Returns an
InboxPostResult
that can be used to check if the request completed successfully.If callback isn’t
None
, it is called with anInboxPostResult
instance when the request has completed.
-
get_starred
(canonical_username=None)[source]¶ Get the starred
Playlist
for the user withcanonical_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 withcanonical_username
.If
canonical_username
isn’t specified, the published container for the currently logged in user is returned.
-
get_link
(uri)[source]¶ 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 beLinkType.LOCALTRACK
for the track’s link.Track.is_local
will beTrue
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.
- The track’s URI will be of the form
-
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’tNone
, it is expected to be a callable that accepts a single argument, anImage
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
.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
query
string 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
callback
isn’tNone
, it is expected to be a callable that accepts a single argument, aSearch
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 theSearch
to see how many results exists, and to figure out how many searches you’ll need to make to retrieve everything.search_type
is aSearchType
value. It defaults toSearchType.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 aToplistType
instance that specifies the type of toplist to create.region
is either aToplistRegion
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
isToplistRegion.USER
andcanonical_username
isn’t specified, the region of the current user will be used. Ifcanonical_username
is specified, the region of the specified user will be used instead.If
callback
isn’tNone
, it is expected to be a callable that accepts a single argument, aToplist
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 toon()
Raises
AssertionError
if 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
event
isNone
.
-
off
(event=None, listener=None)¶ Remove a
listener
that was to be called onevent
.If
listener
isNone
, all listeners for the givenevent
will be removed.If
event
isNone
, all listeners for all events on this object will be removed.
-
on
(event, listener, *user_args)¶ Register a
listener
to 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 theevent
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
= '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:
-
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.OK
error when the problem is resolved.Parameters:
-
MESSAGE_TO_USER
= '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
- session (
-
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 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
- session (
-
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 session - data (text) – the message
- session (
-
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.
Parameters:
-
USER_INFO_UPDATED
= 'user_info_updated'¶ Called when anything related to
User
objects 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_STATS
event for theSTART_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
= 'stop_playback'¶ Called when audio playback should stop.
You need to implement a listener for the
GET_AUDIO_BUFFER_STATS
event for theSTOP_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
= '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 sessionReturns: an AudioBufferStats
instance
-
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
blob
argument can be stored and later passed tologin()
to login without storing the user’s password.Parameters: - session (
Session
) – the current session - blob (bytestring) – the authentication blob
- session (
-
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.
Parameters:
-