Created
March 1, 2016 21:31
-
-
Save LordSputnik/a4eae479f50c47388f0a to your computer and use it in GitHub Desktop.
Python Last.fm top tracks example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pylast | |
API_KEY = '<ADD KEY HERE>' | |
API_SECRET = '<ADD SECRET HERE>' | |
username = "BenOckmore" | |
password_hash = pylast.md5("<ADD PASS HERE>") | |
network = pylast.LastFMNetwork(api_key = API_KEY) | |
class CustomUser(pylast.User): | |
def __init__(self, *args, **kwargs): | |
super(CustomUser, self).__init__(*args, **kwargs) | |
def _get_things( | |
self, method, thing, thing_type, params=None, cacheable=True | |
): | |
"""Returns a list of the most played thing_types by this thing.""" | |
from pylast import TopItem, _extract, _number | |
doc = self._request( | |
self.ws_prefix + "." + method, cacheable, params) | |
toptracks_node = doc.getElementsByTagName('toptracks')[0] | |
total_pages = int(toptracks_node.getAttribute('totalPages')) | |
seq = [] | |
for node in doc.getElementsByTagName(thing): | |
title = _extract(node, "name") | |
artist = _extract(node, "name", 1) | |
mbid = _extract(node, "mbid") | |
playcount = _number(_extract(node, "playcount")) | |
thing = thing_type(artist, title, self.network) | |
thing.mbid = mbid | |
seq.append(TopItem(thing, playcount)) | |
return seq, total_pages | |
def get_top_tracks( | |
self, period=pylast.PERIOD_OVERALL, limit=None, page=1, cacheable=True): | |
"""Returns the top tracks played by a user. | |
* period: The period of time. Possible values: | |
o PERIOD_OVERALL | |
o PERIOD_7DAYS | |
o PERIOD_1MONTH | |
o PERIOD_3MONTHS | |
o PERIOD_6MONTHS | |
o PERIOD_12MONTHS | |
""" | |
params = self._get_params() | |
params['period'] = period | |
params['page'] = page | |
if limit: | |
params['limit'] = limit | |
return self._get_things( | |
"getTopTracks", "track", pylast.Track, params, cacheable) | |
my_user = CustomUser('BenOckmore', network) | |
params = my_user._get_params() | |
params['period'] = pylast.PERIOD_OVERALL | |
params['limit'] = 100 | |
page = 1 | |
results,total_pages = my_user.get_top_tracks(page=page) | |
print total_pages | |
while len(results) != 0: | |
for track in results: | |
print track.item.title, track.item.mbid, track.weight | |
page += 1 | |
results,total_pages = my_user.get_top_tracks(page=page) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment