From 85f15b7261386985e8bb7f9b357e55b5f21c21a7 Mon Sep 17 00:00:00 2001 From: kaliko Date: Sat, 22 Feb 2014 02:32:44 +0100 Subject: [PATCH] Add toptrack method for Last.fm webservice --- sima/lib/cache.py | 19 +++++++++++-------- sima/lib/simafm.py | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/sima/lib/cache.py b/sima/lib/cache.py index d717561..c4170de 100644 --- a/sima/lib/cache.py +++ b/sima/lib/cache.py @@ -35,13 +35,16 @@ from ..utils.filelock import FileLock class BaseCache: def get(self, key): - raise NotImplemented() + """Get cache value""" + raise NotImplementedError def set(self, key, value): - raise NotImplemented() + """Set cache value""" + raise NotImplementedError def delete(self, key): - raise NotImplemented() + """Remove cache value""" + raise NotImplementedError class DictCache(BaseCache): @@ -72,8 +75,8 @@ class FileCache: if not os.path.isdir(self.directory): os.mkdir(self.directory) - def encode(self, x): - return md5(x.encode('utf-8')).hexdigest() + def encode(self, val): + return md5(val.encode('utf-8')).hexdigest() def _fn(self, name): return os.path.join(self.directory, self.encode(name)) @@ -86,15 +89,15 @@ class FileCache: def set(self, key, value): name = self._fn(key) with FileLock(name): - with codecs.open(name, 'w+b') as fh: - dump(value, fh) + with codecs.open(name, 'w+b') as flh: + dump(value, flh) def delete(self, key): if not self.forever: os.remove(self._fn(key)) def __iter__(self): - for dirpath, dirnames, filenames in os.walk(self.directory): + for dirpath, _, filenames in os.walk(self.directory): for item in filenames: name = os.path.join(dirpath, item) yield load(codecs.open(name, 'rb')) diff --git a/sima/lib/simafm.py b/sima/lib/simafm.py index 04e736f..8d82d52 100644 --- a/sima/lib/simafm.py +++ b/sima/lib/simafm.py @@ -30,6 +30,7 @@ from requests import Session, Request, Timeout, ConnectionError from sima import LFM, SOCKET_TIMEOUT, WAIT_BETWEEN_REQUESTS from sima.lib.meta import Artist +from sima.lib.track import Track from sima.lib.http import CacheController from sima.utils.utils import WSError, WSNotFound, WSTimeout, WSHTTPError @@ -144,6 +145,26 @@ class SimaFM: for art in ans.get('similarartists').get('artist'): yield Artist(name=art.get('name'), mbid=art.get('mbid', None)) + def get_toptrack(self, artist=None): + """Fetch artist top tracks + """ + payload = self._forge_payload(artist, method='top') + ans = self._fetch(payload) + tops = ans.get('toptracks').get('track') + art = { + 'artist': artist.name, + 'musicbrainz_artistid': artist.mbid, + } + for song in tops: + for key in ['artist', 'streamable', 'listeners', + 'url', 'image', '@attr']: + if key in song: + song.pop(key) + song.update(art) + song.update(title=song.pop('name')) + song.update(time=song.pop('duration')) + yield Track(**song) + #return tops # VIM MODLINE # vim: ai ts=4 sw=4 sts=4 expandtab -- 2.39.5