corrected the issue 5. changed method names and instance variable names to follow PEP8.

master
Abhinav Sarkar 2008-12-30 10:27:13 +00:00
parent 168046cf98
commit c6bd6ec95f
19 changed files with 604 additions and 595 deletions

View File

@ -8,7 +8,7 @@ from album import Album
from api import Api
from artist import Artist
from base import LastfmBase
from error import LastfmError
from error import Error
from event import Event
from geo import Location, Country
from group import Group
@ -19,6 +19,6 @@ from tasteometer import Tasteometer
from track import Track
from user import User
__all__ = ['LastfmError', 'Api', 'Album', 'Artist', 'Event',
__all__ = ['Error', 'Api', 'Album', 'Artist', 'Event',
'Location', 'Country', 'Group', 'Playlist', 'Tag',
'Tasteometer', 'Track', 'User', 'Registry']

View File

@ -16,12 +16,12 @@ class Album(Taggable, LastfmBase):
id = None,
mbid = None,
url = None,
releaseDate = None,
release_date = None,
image = None,
stats = None,
topTags = None):
top_tags = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
Taggable.init(self, api)
self.__api = api
self.__name = name
@ -29,7 +29,7 @@ class Album(Taggable, LastfmBase):
self.__id = id
self.__mbid = mbid
self.__url = url
self.__releaseDate = releaseDate
self.__release_date = release_date
self.__image = image
self.__stats = stats and Stats(
subject = self,
@ -38,7 +38,7 @@ class Album(Taggable, LastfmBase):
match = stats.match,
rank = stats.rank
)
self.__topTags = topTags
self.__top_tags = top_tags
@property
def name(self):
@ -54,53 +54,53 @@ class Album(Taggable, LastfmBase):
def id(self):
"""id of the album"""
if self.__id is None:
self._fillInfo()
self._fill_info()
return self.__id
@property
def mbid(self):
"""mbid of the album"""
if self.__mbid is None:
self._fillInfo()
self._fill_info()
return self.__mbid
@property
def url(self):
"""url of the album's page"""
if self.__url is None:
self._fillInfo()
self._fill_info()
return self.__url
@property
def releaseDate(self):
def release_date(self):
"""release date of the album"""
if self.__releaseDate is None:
self._fillInfo()
return self.__releaseDate
if self.__release_date is None:
self._fill_info()
return self.__release_date
@property
def image(self):
"""cover images of the album"""
if self.__image is None:
self._fillInfo()
self._fill_info()
return self.__image
@property
def stats(self):
"""stats related to the album"""
if self.__stats is None:
self._fillInfo()
self._fill_info()
return self.__stats
@LastfmBase.cachedProperty
def topTags(self):
def top_tags(self):
"""top tags for the album"""
params = {'method': 'album.getInfo'}
if self.artist and self.name:
params.update({'artist': self.artist.name, 'album': self.name})
elif self.mbid:
params.update({'mbid': self.mbid})
data = self.__api._fetchData(params).find('album')
data = self.__api._fetch_data(params).find('album')
return [
Tag(
self.__api,
@ -111,8 +111,8 @@ class Album(Taggable, LastfmBase):
for t in data.findall('toptags/tag')
]
@LastfmBase.topProperty("topTags")
def topTag(self):
@LastfmBase.topProperty("top_tags")
def top_tag(self):
"""top tag for the album"""
pass
@ -120,34 +120,34 @@ class Album(Taggable, LastfmBase):
def playlist(self):
return Playlist.fetch(self.__api, "lastfm://playlist/album/%s" % self.id)
def _defaultParams(self, extraParams = None):
def _default_params(self, extra_params = None):
if not (self.artist and self.name):
raise LastfmInvalidParametersError("artist and album have to be provided.")
raise InvalidParametersError("artist and album have to be provided.")
params = {'artist': self.artist.name, 'album': self.name}
if extraParams is not None:
params.update(extraParams)
if extra_params is not None:
params.update(extra_params)
return params
@staticmethod
def _fetchData(api,
def _fetch_data(api,
artist = None,
album = None,
mbid = None):
params = {'method': 'album.getInfo'}
if not ((artist and album) or mbid):
raise LastfmInvalidParametersError("either (artist and album) or mbid has to be given as argument.")
raise InvalidParametersError("either (artist and album) or mbid has to be given as argument.")
if artist and album:
params.update({'artist': artist, 'album': album})
elif mbid:
params.update({'mbid': mbid})
return api._fetchData(params).find('album')
return api._fetch_data(params).find('album')
def _fillInfo(self):
data = Album._fetchData(self.__api, self.artist.name, self.name)
def _fill_info(self):
data = Album._fetch_data(self.__api, self.artist.name, self.name)
self.__id = int(data.findtext('id'))
self.__mbid = data.findtext('mbid')
self.__url = data.findtext('url')
self.__releaseDate = data.findtext('releasedate') and data.findtext('releasedate').strip() and \
self.__release_date = data.findtext('releasedate') and data.findtext('releasedate').strip() and \
datetime(*(time.strptime(data.findtext('releasedate').strip(), '%d %b %Y, 00:00')[0:6]))
self.__image = dict([(i.get('size'), i.text) for i in data.findall('image')])
self.__stats = Stats(
@ -155,7 +155,7 @@ class Album(Taggable, LastfmBase):
listeners = int(data.findtext('listeners')),
playcount = int(data.findtext('playcount')),
)
self.__topTags = [
self.__top_tags = [
Tag(
self.__api,
subject = self,
@ -166,11 +166,11 @@ class Album(Taggable, LastfmBase):
]
@staticmethod
def getInfo(api,
def get_info(api,
artist = None,
album = None,
mbid = None):
data = Album._fetchData(api, artist, album, mbid)
data = Album._fetch_data(api, artist, album, mbid)
a = Album(
api,
name = data.findtext('name'),
@ -179,18 +179,18 @@ class Album(Taggable, LastfmBase):
name = data.findtext('artist'),
),
)
a._fillInfo()
a._fill_info()
return a
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash("%s%s" % (kwds['name'], hash(kwds['artist'])))
except KeyError:
raise LastfmInvalidParametersError("name and artist have to be provided for hashing")
raise InvalidParametersError("name and artist have to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name, artist = self.artist)
return self.__class__.hash_func(name = self.name, artist = self.artist)
def __eq__(self, other):
if self.id and other.id:
@ -215,7 +215,7 @@ import time
from api import Api
from artist import Artist
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from playlist import Playlist
from stats import Stats
from tag import Tag

View File

@ -15,54 +15,54 @@ class Api(object):
SEARCH_XMLNS = "http://a9.com/-/spec/opensearch/1.1/"
def __init__(self,
apiKey,
api_key,
secret = None,
sessionKey = None,
session_key = None,
input_encoding=None,
request_headers=None,
no_cache = False,
debug = False):
self.__apiKey = apiKey
self.__api_key = api_key
self.__secret = secret
self.__sessionKey = sessionKey
self.__session_key = session_key
self._cache = FileCache()
self._urllib = urllib2
self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
self._InitializeRequestHeaders(request_headers)
self._InitializeUserAgent()
self._initialize_request_headers(request_headers)
self._initialize_user_agent()
self._input_encoding = input_encoding
self._no_cache = no_cache
self._debug = debug
self._lastFetchTime = datetime.now()
self._last_fetch_time = datetime.now()
@property
def apiKey(self):
return self.__apiKey
def api_key(self):
return self.__api_key
@property
def secret(self):
return self.__secret
@property
def sessionKey(self):
return self.__sessionKey
def session_key(self):
return self.__session_key
def setSessionKey(self):
params = {'method': 'auth.getSession', 'token': self.authToken}
self.__sessionKey = self._fetchData(params, sign = True).findtext('session/key')
self.__authToken = None
def set_session_key(self):
params = {'method': 'auth.getSession', 'token': self.auth_token}
self.__session_key = self._fetch_data(params, sign = True).findtext('session/key')
self.__auth_token = None
@LastfmBase.cachedProperty
def authToken(self):
def auth_token(self):
params = {'method': 'auth.getToken'}
return self._fetchData(params, sign = True).findtext('token')
return self._fetch_data(params, sign = True).findtext('token')
@LastfmBase.cachedProperty
def authUrl(self):
return "http://www.last.fm/api/auth/?api_key=%s&token=%s" % (self.apiKey, self.authToken)
def auth_url(self):
return "http://www.last.fm/api/auth/?api_key=%s&token=%s" % (self.api_key, self.auth_token)
def setCache(self, cache):
def set_cache(self, cache):
'''Override the default cache. Set to None to prevent caching.
Args:
@ -70,7 +70,7 @@ class Api(object):
'''
self._cache = cache
def setUrllib(self, urllib):
def set_urllib(self, urllib):
'''Override the default urllib implementation.
Args:
@ -78,7 +78,7 @@ class Api(object):
'''
self._urllib = urllib
def setCacheTimeout(self, cache_timeout):
def set_cache_timeout(self, cache_timeout):
'''Override the default cache timeout.
Args:
@ -86,7 +86,7 @@ class Api(object):
'''
self._cache_timeout = cache_timeout
def setUserAgent(self, user_agent):
def set_user_agent(self, user_agent):
'''Override the default user agent
Args:
@ -94,84 +94,84 @@ class Api(object):
'''
self._request_headers['User-Agent'] = user_agent
def getAlbum(self,
def get_album(self,
artist = None,
album = None,
mbid = None):
if isinstance(artist, Artist):
artist = artist.name
return Album.getInfo(self, artist, album, mbid)
return Album.get_info(self, artist, album, mbid)
def getArtist(self,
def get_artist(self,
artist = None,
mbid = None):
return Artist.getInfo(self, artist, mbid)
return Artist.get_info(self, artist, mbid)
def searchArtist(self,
def search_artist(self,
artist,
limit = None):
return Artist.search(self, searchItem = artist, limit = limit)
return Artist.search(self, search_item = artist, limit = limit)
def getEvent(self, event):
return Event.getInfo(self, event)
def get_event(self, event):
return Event.get_info(self, event)
def getLocation(self, name):
def get_location(self, name):
return Location(self, name = name)
def getCountry(self, name):
def get_country(self, name):
return Country(self, name = name)
def getGroup(self, name):
def get_group(self, name):
return Group(self, name = name)
def fetchPlaylist(self, url):
def fetch_playlist(self, url):
return Playlist.fetch(self, url)
def getTag(self, name):
def get_tag(self, name):
return Tag(self, name = name)
def getGlobalTopTags(self):
return Tag.getTopTags(self)
def get_global_top_tags(self):
return Tag.get_top_tags(self)
def searchTag(self,
def search_tag(self,
tag,
limit = None):
return Tag.search(self, searchItem = tag, limit = limit)
return Tag.search(self, search_item = tag, limit = limit)
def compareTaste(self,
def compare_taste(self,
type1, type2,
value1, value2,
limit = None):
return Tasteometer.compare(self, type1, type2, value1, value2, limit)
def getTrack(self, track, artist = None, mbid = None):
def get_track(self, track, artist = None, mbid = None):
if isinstance(artist, Artist):
artist = artist.name
return Track.getInfo(self, artist, track, mbid)
return Track.get_info(self, artist, track, mbid)
def searchTrack(self,
def search_track(self,
track,
artist = None,
limit = None):
if isinstance(artist, Artist):
artist = artist.name
return Track.search(self, searchItem = track, limit = limit, artist = artist)
return Track.search(self, search_item = track, limit = limit, artist = artist)
def getUser(self, name):
def get_user(self, name):
user = None
try:
user = User(self, name = name)
user.friends
except LastfmError, e:
except Error, e:
raise e
return user
def getAuthenticatedUser(self):
if self.sessionKey is not None:
return User.getAuthenticatedUser(self)
def get_authenticated_user(self):
if self.session_key is not None:
return User.get_authenticated_user(self)
return None
def _BuildUrl(self, url, path_elements=None, extra_params=None):
def _build_url(self, url, path_elements=None, extra_params=None):
# Break url into consituent parts
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
path = path.replace(' ', '+')
@ -186,7 +186,7 @@ class Api(object):
# Add any additional query parameters to the query string
if extra_params and len(extra_params) > 0:
extra_query = self._EncodeParameters(extra_params)
extra_query = self._encode_parameters(extra_params)
# Add it to the existing query
if query:
query += '&' + extra_query
@ -196,31 +196,31 @@ class Api(object):
# Return the rebuilt URL
return urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
def _InitializeRequestHeaders(self, request_headers):
def _initialize_request_headers(self, request_headers):
if request_headers:
self._request_headers = request_headers
else:
self._request_headers = {}
def _InitializeUserAgent(self):
def _initialize_user_agent(self):
user_agent = 'Python-urllib/%s (python-lastfm/%s)' % \
(self._urllib.__version__, __version__)
self.setUserAgent(user_agent)
self.set_user_agent(user_agent)
def _GetOpener(self, url):
def _get_opener(self, url):
opener = self._urllib.build_opener()
if self._urllib._opener is not None:
opener = self._urllib.build_opener(*self._urllib._opener.handlers)
opener.addheaders = self._request_headers.items()
return opener
def _Encode(self, s):
def _encode(self, s):
if self._input_encoding:
return unicode(s, self._input_encoding).encode('utf-8')
else:
return unicode(s).encode('utf-8')
def _EncodeParameters(self, parameters):
def _encode_parameters(self, parameters):
'''Return a string in key=value&key=value form
Values of None are not included in the output string.
@ -237,19 +237,19 @@ class Api(object):
else:
keys = parameters.keys()
keys.sort()
return urllib.urlencode([(k, self._Encode(parameters[k])) for k in keys if parameters[k] is not None])
return urllib.urlencode([(k, self._encode(parameters[k])) for k in keys if parameters[k] is not None])
def _ReadUrlData(self, opener, url, data = None):
def _read_url_data(self, opener, url, data = None):
now = datetime.now()
delta = now - self._lastFetchTime
delta = now - self._last_fetch_time
delta = delta.seconds + float(delta.microseconds)/1000000
if delta < Api.FETCH_INTERVAL:
time.sleep(Api.FETCH_INTERVAL - delta)
url_data = opener.open(url, data).read()
self._lastFetchTime = datetime.now()
self._last_fetch_time = datetime.now()
return url_data
def _fetchUrl(self,
def _fetch_url(self,
url,
parameters = None,
no_cache = False):
@ -265,16 +265,16 @@ class Api(object):
A string containing the body of the response.
'''
# Add key/value parameters to the query string of the url
url = self._BuildUrl(url, extra_params=parameters)
url = self._build_url(url, extra_params=parameters)
if self._debug:
print url
# Get a url opener that can handle basic auth
opener = self._GetOpener(url)
opener = self._get_opener(url)
# Open and return the URL immediately if we're not going to cache
if no_cache or not self._cache or not self._cache_timeout:
try:
url_data = self._ReadUrlData(opener, url)
url_data = self._read_url_data(opener, url)
except urllib2.HTTPError, e:
url_data = e.read()
else:
@ -287,7 +287,7 @@ class Api(object):
# If the cached version is outdated then fetch another and store it
if not last_cached or time.time() >= last_cached + self._cache_timeout:
try:
url_data = self._ReadUrlData(opener, url)
url_data = self._read_url_data(opener, url)
except urllib2.HTTPError, e:
url_data = e.read()
self._cache.Set(key, url_data)
@ -297,49 +297,49 @@ class Api(object):
# Always return the latest version
return url_data
def _fetchData(self,
def _fetch_data(self,
params,
sign = False,
session = False,
no_cache = False):
params['api_key'] = self.apiKey
params['api_key'] = self.api_key
if session:
if self.sessionKey is not None:
params['sk'] = self.sessionKey
if self.session_key is not None:
params['sk'] = self.session_key
else:
raise LastfmAuthenticationFailedError("session key must be present to call this method")
raise AuthenticationFailedError("session key must be present to call this method")
if sign:
params['api_sig'] = self._getApiSig(params)
params['api_sig'] = self._get_api_sig(params)
xml = self._fetchUrl(Api.API_ROOT_URL, params, no_cache = self._no_cache or no_cache)
return self._checkXML(xml)
xml = self._fetch_url(Api.API_ROOT_URL, params, no_cache = self._no_cache or no_cache)
return self._check_XML(xml)
def _postUrl(self,
def _post_url(self,
url,
parameters):
url = self._BuildUrl(url)
url = self._build_url(url)
if self._debug:
print url
data = self._EncodeParameters(parameters)
opener = self._GetOpener(url)
url_data = self._ReadUrlData(opener, url, data)
data = self._encode_parameters(parameters)
opener = self._get_opener(url)
url_data = self._read_url_data(opener, url, data)
return url_data
def _postData(self, params):
params['api_key'] = self.apiKey
def _post_data(self, params):
params['api_key'] = self.api_key
if self.sessionKey is not None:
params['sk'] = self.sessionKey
if self.session_key is not None:
params['sk'] = self.session_key
else:
raise LastfmAuthenticationFailedError("session key must be present to call this method")
raise AuthenticationFailedError("session key must be present to call this method")
params['api_sig'] = self._getApiSig(params)
xml = self._postUrl(Api.API_ROOT_URL, params)
return self._checkXML(xml)
params['api_sig'] = self._get_api_sig(params)
xml = self._post_url(Api.API_ROOT_URL, params)
return self._check_XML(xml)
def _getApiSig(self, params):
def _get_api_sig(self, params):
if self.secret is not None:
keys = params.keys()[:]
keys.sort()
@ -350,25 +350,25 @@ class Api(object):
hashed_sig = md5.new(sig).hexdigest()
return hashed_sig
else:
raise LastfmAuthenticationFailedError("api secret must be present to call this method")
raise AuthenticationFailedError("api secret must be present to call this method")
def _checkXML(self, xml):
def _check_XML(self, xml):
data = None
try:
data = ElementTree.XML(xml)
except SyntaxError, e:
raise LastfmOperationFailedError("Error in parsing XML: %s" % e)
raise OperationFailedError("Error in parsing XML: %s" % e)
if data.get('status') != "ok":
code = int(data.find("error").get('code'))
message = data.findtext('error')
if code in errorMap.keys():
raise errorMap[code](message, code)
else:
raise LastfmError(message, code)
raise Error(message, code)
return data
def __repr__(self):
return "<lastfm.Api: %s>" % self.__apiKey
return "<lastfm.Api: %s>" % self.__api_key
from datetime import datetime
import md5
@ -380,7 +380,7 @@ import urlparse
from album import Album
from artist import Artist
from error import errorMap, LastfmError, LastfmOperationFailedError, LastfmInvalidResourceError, LastfmAuthenticationFailedError
from error import errorMap, Error, OperationFailedError, AuthenticationFailedError
from event import Event
from filecache import FileCache
from geo import Location, Country
@ -401,4 +401,4 @@ else:
try:
import ElementTree
except ImportError:
raise LastfmError("Install ElementTree package for using python-lastfm")
raise Error("Install ElementTree package for using python-lastfm")

View File

@ -21,10 +21,10 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
streamable = None,
stats = None,
similar = None,
topTags = None,
top_tags = None,
bio = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
Taggable.init(self, api)
Sharable.init(self, api)
self.__api = api
@ -41,7 +41,7 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
rank = stats.rank
)
self.__similar = similar
self.__topTags = topTags
self.__top_tags = top_tags
self.__bio = bio and Wiki(
subject = self,
published = bio.published,
@ -58,50 +58,50 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
def mbid(self):
"""mbid of the artist"""
if self.__mbid is None:
self._fillInfo()
self._fill_info()
return self.__mbid
@property
def url(self):
"""url of the artist's page"""
if self.__url is None:
self._fillInfo()
self._fill_info()
return self.__url
@property
def image(self):
"""images of the artist"""
if self.__image is None:
self._fillInfo()
self._fill_info()
return self.__image
@property
def streamable(self):
"""is the artist streamable"""
if self.__streamable is None:
self._fillInfo()
self._fill_info()
return self.__streamable
@property
def stats(self):
"""stats for the artist"""
if self.__stats is None:
self._fillInfo()
self._fill_info()
return self.__stats
def _defaultParams(self, extraParams = None):
def _default_params(self, extraParams = None):
if not self.name:
raise LastfmInvalidParametersError("artist has to be provided.")
raise InvalidParametersError("artist has to be provided.")
params = {'artist': self.name}
if extraParams is not None:
params.update(extraParams)
return params
def getSimilar(self, limit = None):
params = self._defaultParams({'method': 'artist.getSimilar'})
def get_similar(self, limit = None):
params = self._default_params({'method': 'artist.getSimilar'})
if limit is not None:
params.update({'limit': limit})
data = self.__api._fetchData(params).find('similarartists')
data = self.__api._fetch_data(params).find('similarartists')
self.__similar = [
Artist(
self.__api,
@ -123,21 +123,21 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
def similar(self):
"""artists similar to this artist"""
if self.__similar is None or len(self.__similar) < 6:
return self.getSimilar()
return self.get_similar()
return self.__similar[:]
@LastfmBase.topProperty("similar")
def mostSimilar(self):
def most_similar(self):
"""artist most similar to this artist"""
pass
@property
def topTags(self):
def top_tags(self):
"""top tags for the artist"""
if self.__topTags is None or len(self.__topTags) < 6:
params = self._defaultParams({'method': 'artist.getTopTags'})
data = self.__api._fetchData(params).find('toptags')
self.__topTags = [
if self.__top_tags is None or len(self.__top_tags) < 6:
params = self._default_params({'method': 'artist.getTopTags'})
data = self.__api._fetch_data(params).find('toptags')
self.__top_tags = [
Tag(
self.__api,
subject = self,
@ -146,10 +146,10 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
)
for t in data.findall('tag')
]
return self.__topTags[:]
return self.__top_tags[:]
@LastfmBase.topProperty("topTags")
def topTag(self):
@LastfmBase.topProperty("top_tags")
def top_tag(self):
"""top tag for the artist"""
pass
@ -157,25 +157,25 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
def bio(self):
"""biography of the artist"""
if self.__bio is None:
self._fillInfo()
self._fill_info()
return self.__bio
@LastfmBase.cachedProperty
def events(self):
"""events for the artist"""
params = self._defaultParams({'method': 'artist.getEvents'})
data = self.__api._fetchData(params).find('events')
params = self._default_params({'method': 'artist.getEvents'})
data = self.__api._fetch_data(params).find('events')
return [
Event.createFromData(self.__api, e)
Event.create_from_data(self.__api, e)
for e in data.findall('event')
]
@LastfmBase.cachedProperty
def topAlbums(self):
def top_albums(self):
"""top albums of the artist"""
params = self._defaultParams({'method': 'artist.getTopAlbums'})
data = self.__api._fetchData(params).find('topalbums')
params = self._default_params({'method': 'artist.getTopAlbums'})
data = self.__api._fetch_data(params).find('topalbums')
return [
Album(
@ -195,16 +195,16 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
for a in data.findall('album')
]
@LastfmBase.topProperty("topAlbums")
def topAlbum(self):
@LastfmBase.topProperty("top_albums")
def top_album(self):
"""top album of the artist"""
pass
@LastfmBase.cachedProperty
def topFans(self):
def top_fans(self):
"""top fans of the artist"""
params = self._defaultParams({'method': 'artist.getTopFans'})
data = self.__api._fetchData(params).find('topfans')
params = self._default_params({'method': 'artist.getTopFans'})
data = self.__api._fetch_data(params).find('topfans')
return [
User(
self.__api,
@ -220,16 +220,16 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
for u in data.findall('user')
]
@LastfmBase.topProperty("topFans")
def topFan(self):
@LastfmBase.topProperty("top_fans")
def top_fan(self):
"""top fan of the artist"""
pass
@LastfmBase.cachedProperty
def topTracks(self):
def top_tracks(self):
"""top tracks of the artist"""
params = self._defaultParams({'method': 'artist.getTopTracks'})
data = self.__api._fetchData(params).find('toptracks')
params = self._default_params({'method': 'artist.getTopTracks'})
data = self.__api._fetch_data(params).find('toptracks')
return [
Track(
self.__api,
@ -249,13 +249,13 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
for t in data.findall('track')
]
@LastfmBase.topProperty("topTracks")
def topTrack(self):
@LastfmBase.topProperty("top_tracks")
def top_track(self):
"""topmost fan of the artist"""
pass
@staticmethod
def _searchYieldFunc(api, artist):
def _search_yield_func(api, artist):
return Artist(
api,
name = artist.findtext('name'),
@ -265,20 +265,20 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
streamable = (artist.findtext('streamable') == '1'),
)
@staticmethod
def _fetchData(api,
def _fetch_data(api,
artist = None,
mbid = None):
params = {'method': 'artist.getInfo'}
params = {'method': 'artist.get_info'}
if not (artist or mbid):
raise LastfmInvalidParametersError("either artist or mbid has to be given as argument.")
raise InvalidParametersError("either artist or mbid has to be given as argument.")
if artist:
params.update({'artist': artist})
elif mbid:
params.update({'mbid': mbid})
return api._fetchData(params).find('artist')
return api._fetch_data(params).find('artist')
def _fillInfo(self):
data = Artist._fetchData(self.__api, self.name)
def _fill_info(self):
data = Artist._fetch_data(self.__api, self.name)
self.__name = data.findtext('name')
self.__mbid = data.findtext('mbid')
self.__url = data.findtext('url')
@ -299,7 +299,7 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
)
for a in data.findall('similar/artist')
]
self.__topTags = [
self.__top_tags = [
Tag(
self.__api,
subject = self,
@ -319,27 +319,27 @@ class Artist(LastfmBase, Taggable, Sharable, Searchable):
)
@staticmethod
def getInfo(api,
def get_info(api,
artist = None,
mbid = None):
data = Artist._fetchData(api, artist, mbid)
data = Artist._fetch_data(api, artist, mbid)
a = Artist(api, name = data.findtext('name'))
a._fillInfo()
a._fill_info()
return a
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['name'].lower())
except KeyError:
try:
return hash(args[1].lower())
except IndexError:
raise LastfmInvalidParametersError("name has to be provided for hashing")
raise InvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
return self.__class__.hash_func(name = self.name)
def __eq__(self, other):
if self.mbid and other.mbid:
@ -359,7 +359,7 @@ import time
from album import Album
from api import Api
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from event import Event
from stats import Stats
from tag import Tag

View File

@ -27,7 +27,7 @@ class LastfmBase(object):
inst.init(*args, **kwds)
return inst
key = cls.hashFunc(*args, **kwds)
key = cls.hash_func(*args, **kwds)
if subject is not None:
key = (hash(subject), key)
@ -77,7 +77,7 @@ class LastfmBase(object):
try:
cp = copy.copy(cacheAttribute)
return cp
except LastfmError:
except Error:
return cacheAttribute
return property(fget = wrapper, doc = func.__doc__)
@ -96,4 +96,4 @@ class LastfmBase(object):
import sys
import copy
from error import LastfmError
from error import Error

View File

@ -4,77 +4,80 @@ __author__ = "Abhinav Sarkar <abhinav@abhinavsarkar.net>"
__version__ = "0.2"
__license__ = "GNU Lesser General Public License"
class LastfmError(Exception):
"""Base class for Lastfm errors"""
def __init__(self,
message = None,
code = None):
self.__code = code
self.__message = message
class BaseError(Exception):
"""Base class for Lastfm errors"""
def __init__(self,
message = None,
code = None):
super(BaseError, self).__init__()
self.__code = code
self.__message = message
@property
def code(self):
return self.__code
@property
def code(self):
return self.__code
@property
def message(self):
return self.__message
def __str__(self):
return "%s" % self.message
@property
def message(self):
return self.__message
def __str__(self):
return "%s" % self.message
class Error(BaseError):
pass
class LastfmInvalidServiceError(LastfmError):#2
pass
class InvalidServiceError(BaseError):#2
pass
class LastfmInvalidMethodError(LastfmError):#3
pass
class InvalidMethodError(BaseError):#3
pass
class LastfmAuthenticationFailedError(LastfmError):#4
pass
class AuthenticationFailedError(BaseError):#4
pass
class LastfmInvalidFormatError(LastfmError):#5
pass
class InvalidFormatError(BaseError):#5
pass
class LastfmInvalidParametersError(LastfmError):#6
pass
class InvalidParametersError(BaseError):#6
pass
class LastfmInvalidResourceError(LastfmError):#7
pass
class InvalidResourceError(BaseError):#7
pass
class LastfmOperationFailedError(LastfmError):#8
pass
class OperationFailedError(BaseError):#8
pass
class LastfmInvalidSessionKeyError(LastfmError):#9
pass
class InvalidSessionKeyError(BaseError):#9
pass
class LastfmInvalidApiKeyError(LastfmError):#10
pass
class InvalidApiKeyError(BaseError):#10
pass
class LastfmServiceOfflineError(LastfmError):#11
pass
class ServiceOfflineError(BaseError):#11
pass
class LastfmSubscribersOnlyError(LastfmError):#12
pass
class SubscribersOnlyError(BaseError):#12
pass
class LastfmTokenNotAuthorizedError(LastfmError):#14
pass
class TokenNotAuthorizedError(BaseError):#14
pass
class LastfmTokenExpiredError(LastfmError):#15
pass
class TokenExpiredError(BaseError):#15
pass
errorMap = {
1: LastfmError,
2: LastfmInvalidServiceError,
3: LastfmInvalidMethodError,
4: LastfmAuthenticationFailedError,
5: LastfmInvalidFormatError,
6: LastfmInvalidParametersError,
7: LastfmInvalidResourceError,
8: LastfmOperationFailedError,
9: LastfmInvalidSessionKeyError,
10: LastfmInvalidApiKeyError,
11: LastfmServiceOfflineError,
12: LastfmSubscribersOnlyError,
14: LastfmTokenNotAuthorizedError,
15: LastfmTokenExpiredError
}
1: Error,
2: InvalidServiceError,
3: InvalidMethodError,
4: AuthenticationFailedError,
5: InvalidFormatError,
6: InvalidParametersError,
7: InvalidResourceError,
8: OperationFailedError,
9: InvalidSessionKeyError,
10: InvalidApiKeyError,
11: ServiceOfflineError,
12: SubscribersOnlyError,
14: TokenNotAuthorizedError,
15: TokenExpiredError
}

View File

@ -20,15 +20,14 @@ class Event(LastfmBase, Sharable):
artists = None,
headliner = None,
venue = None,
startDate = None,
startTime = None,
start_date = None,
description = None,
image = None,
url = None,
stats = None,
tag = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
Sharable.init(self, api)
self.__api = api
self.__id = id
@ -36,7 +35,7 @@ class Event(LastfmBase, Sharable):
self.__artists = artists
self.__headliner = headliner
self.__venue = venue
self.__startDate = startDate
self.__start_date = start_date
self.__description = description
self.__image = image
self.__url = url
@ -73,9 +72,9 @@ class Event(LastfmBase, Sharable):
return self.__venue
@property
def startDate(self):
def start_date(self):
"""start date of the event"""
return self.__startDate
return self.__start_date
@property
def description(self):
@ -104,30 +103,30 @@ class Event(LastfmBase, Sharable):
def attend(self, status = STATUS_ATTENDING):
if status not in [Event.STATUS_ATTENDING, Event.STATUS_MAYBE, Event.STATUS_NOT]:
LastfmInvalidParametersError("status has to be 0, 1 or 2")
params = self._defaultParams({'method': 'event.attend', 'status': status})
self.__api._postData(params)
InvalidParametersError("status has to be 0, 1 or 2")
params = self._default_params({'method': 'event.attend', 'status': status})
self.__api._post_data(params)
def _defaultParams(self, extraParams = None):
def _default_params(self, extra_params = None):
if not self.id:
raise LastfmInvalidParametersError("id has to be provided.")
raise InvalidParametersError("id has to be provided.")
params = {'event': self.id}
if extraParams is not None:
params.update(extraParams)
if extra_params is not None:
params.update(extra_params)
return params
@staticmethod
def getInfo(api, event):
def get_info(api, event):
params = {'method': 'event.getInfo', 'event': event}
data = api._fetchData(params).find('event')
return Event.createFromData(api, data)
data = api._fetch_data(params).find('event')
return Event.create_from_data(api, data)
@staticmethod
def createFromData(api, data):
startDate = None
def create_from_data(api, data):
start_date = None
if data.findtext('startTime') is not None:
startDate = datetime(*(
start_date = datetime(*(
time.strptime(
"%s %s" % (
data.findtext('startDate').strip(),
@ -138,7 +137,7 @@ class Event(LastfmBase, Sharable):
)
else:
try:
startDate = datetime(*(
start_date = datetime(*(
time.strptime(
data.findtext('startDate').strip(),
'%a, %d %b %Y %H:%M:%S'
@ -146,7 +145,7 @@ class Event(LastfmBase, Sharable):
)
except ValueError:
try:
startDate = datetime(*(
start_date = datetime(*(
time.strptime(
data.findtext('startDate').strip(),
'%a, %d %b %Y'
@ -174,16 +173,16 @@ class Event(LastfmBase, Sharable):
street = data.findtext('venue/location/street'),
postalCode = data.findtext('venue/location/postalcode'),
latitude = float(data.findtext(
'venue/location/{%s}point/{%s}lat' % ((Location.xmlns,)*2)
'venue/location/{%s}point/{%s}lat' % ((Location.XMLNS,)*2)
)),
longitude = float(data.findtext(
'venue/location/{%s}point/{%s}long' % ((Location.xmlns,)*2)
'venue/location/{%s}point/{%s}long' % ((Location.XMLNS,)*2)
)),
timezone = data.findtext('venue/location/timezone')
),
url = data.findtext('venue/url')
),
startDate = startDate,
start_date = start_date,
description = data.findtext('description'),
image = dict([(i.get('size'), i.text) for i in data.findall('image')]),
url = data.findtext('url'),
@ -196,29 +195,29 @@ class Event(LastfmBase, Sharable):
)
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['id'])
except KeyError:
raise LastfmInvalidParametersError("id has to be provided for hashing")
raise InvalidParametersError("id has to be provided for hashing")
def __hash__(self):
return Event.hashFunc(id = self.id)
return Event.hash_func(id = self.id)
def __eq__(self, other):
return self.id == other.id
def __lt__(self, other):
return self.startDate < other.startDate
return self.start_date < other.start_date
def __repr__(self):
return "<lastfm.Event: %s at %s on %s>" % (self.title, self.venue.name, self.startDate.strftime("%x"))
return "<lastfm.Event: %s at %s on %s>" % (self.title, self.venue.name, self.start_date.strftime("%x"))
from datetime import datetime
import time
from api import Api
from artist import Artist
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from geo import Venue, Location, Country
from stats import Stats

View File

@ -10,7 +10,7 @@ from lazylist import lazylist
class Geo(object):
"""A class representing an geographic location."""
@staticmethod
def getEvents(api,
def get_events(api,
location,
latitude = None,
longitude = None,
@ -24,28 +24,28 @@ class Geo(object):
@lazylist
def gen(lst):
data = api._fetchData(params).find('events')
data = api._fetch_data(params).find('events')
totalPages = int(data.attrib['totalpages'])
@lazylist
def gen2(lst, data):
for e in data.findall('event'):
yield Event.createFromData(api, e)
yield Event.create_from_data(api, e)
for e in gen2(data):
yield e
for page in xrange(2, totalPages+1):
params.update({'page': page})
data = api._fetchData(params).find('events')
data = api._fetch_data(params).find('events')
for e in gen2(data):
yield e
return gen()
@staticmethod
def getTopArtists(api, country):
def get_top_artists(api, country):
params = {'method': 'geo.getTopArtists', 'country': country}
data = api._fetchData(params).find('topartists')
data = api._fetch_data(params).find('topartists')
return [
Artist(
api,
@ -63,12 +63,12 @@ class Geo(object):
]
@staticmethod
def getTopTracks(api, country, location = None):
def get_top_tracks(api, country, location = None):
params = {'method': 'geo.getTopTracks', 'country': country}
if location is not None:
params.update({'location': location})
data = api._fetchData(params).find('toptracks')
data = api._fetch_data(params).find('toptracks')
return [
Track(
api,
@ -119,14 +119,14 @@ class Venue(LastfmBase):
return self.__url
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['url'])
except KeyError:
raise LastfmInvalidParametersError("url has to be provided for hashing")
raise InvalidParametersError("url has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(url = self.url)
return self.__class__.hash_func(url = self.url)
def __eq__(self, other):
return self.url == other.url
@ -139,24 +139,24 @@ class Venue(LastfmBase):
class Location(LastfmBase):
"""A class representing a location of an event"""
xmlns = "http://www.w3.org/2003/01/geo/wgs84_pos#"
XMLNS = "http://www.w3.org/2003/01/geo/wgs84_pos#"
def init(self,
api,
city = None,
country = None,
street = None,
postalCode = None,
postal_code = None,
latitude = None,
longitude = None,
timezone = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__city = city
self.__country = country
self.__street = street
self.__postalCode = postalCode
self.__postalCode = postal_code
self.__latitude = latitude
self.__longitude = longitude
self.__timezone = timezone
@ -197,20 +197,20 @@ class Location(LastfmBase):
return self.__timezone
@LastfmBase.cachedProperty
def topTracks(self):
def top_tracks(self):
"""top tracks of the location"""
if self.country is None or self.city is None:
raise LastfmInvalidParametersError("country and city of this location are required for calling this method")
return Geo.getTopTracks(self.__api, self.country.name, self.city)
raise InvalidParametersError("country and city of this location are required for calling this method")
return Geo.get_top_tracks(self.__api, self.country.name, self.city)
@LastfmBase.topProperty("topTracks")
def topTrack(self):
@LastfmBase.topProperty("top_tracks")
def top_track(self):
"""top track of the location"""
pass
def getEvents(self,
def get_events(self,
distance = None):
return Geo.getEvents(self.__api,
return Geo.get_events(self.__api,
self.city,
self.latitude,
self.longitude,
@ -219,25 +219,25 @@ class Location(LastfmBase):
@LastfmBase.cachedProperty
def events(self):
"""events taking place at/around the location"""
return self.getEvents()
return self.get_events()
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash("latlong%s%s" % (kwds['latitude'], kwds['longitude']))
except KeyError:
try:
return hash("name%s" % kwds['city'])
except KeyError:
raise LastfmInvalidParametersError("either latitude and longitude or city has to be provided for hashing")
raise InvalidParametersError("either latitude and longitude or city has to be provided for hashing")
def __hash__(self):
if not self.name:
return self.__class__.hashFunc(
if not self.city:
return self.__class__.hash_func(
latitude = self.latitude,
longitude = self.longitude)
else:
return self.__class__.hashFunc(name = self.city)
return self.__class__.hash_func(name = self.city)
def __eq__(self, other):
return self.latitude == other.latitude and self.longitude == other.longitude
@ -260,7 +260,7 @@ class Country(LastfmBase):
api,
name = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
@ -270,42 +270,42 @@ class Country(LastfmBase):
return self.__name
@LastfmBase.cachedProperty
def topArtists(self):
def top_artists(self):
"""top artists of the country"""
return Geo.getTopArtists(self.__api, self.name)
return Geo.get_top_artists(self.__api, self.name)
@LastfmBase.topProperty("topArtists")
def topArtist(self):
@LastfmBase.topProperty("top_artists")
def top_artist(self):
"""top artist of the country"""
pass
def getTopTracks(self, location = None):
return Geo.getTopTracks(self.__api, self.name, location)
def get_top_tracks(self, location = None):
return Geo.get_top_tracks(self.__api, self.name, location)
@LastfmBase.cachedProperty
def topTracks(self):
def top_tracks(self):
"""top tracks of the country"""
return self.getTopTracks()
return self.get_top_tracks()
@LastfmBase.topProperty("topTracks")
def topTrack(self):
@LastfmBase.topProperty("top_tracks")
def top_track(self):
"""top track of the country"""
pass
@LastfmBase.cachedProperty
def events(self):
"""events taking place at/around the location"""
return Geo.getEvents(self.__api, self.name)
return Geo.get_events(self.__api, self.name)
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['name'])
except KeyError:
raise LastfmInvalidParametersError("name has to be provided for hashing")
raise InvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
return self.__class__.hash_func(name = self.name)
def __eq__(self, other):
return self.name == other.name
@ -318,7 +318,7 @@ class Country(LastfmBase):
from api import Api
from artist import Artist
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from event import Event
from stats import Stats
from track import Track

View File

@ -13,7 +13,7 @@ class Group(LastfmBase):
api,
name = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
@ -22,89 +22,89 @@ class Group(LastfmBase):
return self.__name
@LastfmBase.cachedProperty
def weeklyChartList(self):
def weekly_chart_list(self):
params = {'method': 'group.getWeeklyChartList', 'group': self.name}
data = self.__api._fetchData(params).find('weeklychartlist')
data = self.__api._fetch_data(params).find('weeklychartlist')
return [
WeeklyChart.createFromData(self.__api, self, c)
WeeklyChart.create_from_data(self.__api, self, c)
for c in data.findall('chart')
]
def getWeeklyAlbumChart(self,
def get_weekly_album_chart(self,
start = None,
end = None):
params = {'method': 'group.getWeeklyAlbumChart', 'group': self.name}
params = WeeklyChart._checkWeeklyChartParams(params, start, end)
data = self.__api._fetchData(params).find('weeklyalbumchart')
return WeeklyAlbumChart.createFromData(self.__api, self, data)
params = WeeklyChart._check_weekly_chart_params(params, start, end)
data = self.__api._fetch_data(params).find('weeklyalbumchart')
return WeeklyAlbumChart.create_from_data(self.__api, self, data)
@LastfmBase.cachedProperty
def recentWeeklyAlbumChart(self):
return self.getWeeklyAlbumChart()
def recent_weekly_album_chart(self):
return self.get_weekly_album_chart()
@LastfmBase.cachedProperty
def weeklyAlbumChartList(self):
wcl = list(self.weeklyChartList)
def weekly_album_chart_list(self):
wcl = list(self.weekly_chart_list)
wcl.reverse()
@lazylist
def gen(lst):
for wc in wcl:
yield self.getWeeklyAlbumChart(wc.start, wc.end)
yield self.get_weekly_album_chart(wc.start, wc.end)
return gen()
def getWeeklyArtistChart(self,
def get_weekly_artist_chart(self,
start = None,
end = None):
params = {'method': 'group.getWeeklyArtistChart', 'group': self.name}
params = WeeklyChart._checkWeeklyChartParams(params, start, end)
data = self.__api._fetchData(params).find('weeklyartistchart')
return WeeklyArtistChart.createFromData(self.__api, self, data)
params = WeeklyChart._check_weekly_chart_params(params, start, end)
data = self.__api._fetch_data(params).find('weeklyartistchart')
return WeeklyArtistChart.create_from_data(self.__api, self, data)
@LastfmBase.cachedProperty
def recentWeeklyArtistChart(self):
return self.getWeeklyArtistChart()
def recent_weekly_artist_chart(self):
return self.get_weekly_artist_chart()
@LastfmBase.cachedProperty
def weeklyArtistChartList(self):
wcl = list(self.weeklyChartList)
def weekly_artist_chart_list(self):
wcl = list(self.weekly_chart_list)
wcl.reverse()
@lazylist
def gen(lst):
for wc in wcl:
yield self.getWeeklyArtistChart(wc.start, wc.end)
yield self.get_weekly_artist_chart(wc.start, wc.end)
return gen()
def getWeeklyTrackChart(self,
def get_weekly_track_chart(self,
start = None,
end = None):
params = {'method': 'group.getWeeklyTrackChart', 'group': self.name}
params = WeeklyChart._checkWeeklyChartParams(params, start, end)
data = self.__api._fetchData(params).find('weeklytrackchart')
return WeeklyTrackChart.createFromData(self.__api, self, data)
params = WeeklyChart._check_weekly_chart_params(params, start, end)
data = self.__api._fetch_data(params).find('weeklytrackchart')
return WeeklyTrackChart.create_from_data(self.__api, self, data)
@LastfmBase.cachedProperty
def recentWeeklyTrackChart(self):
return self.getWeeklyTrackChart()
def recent_weekly_track_chart(self):
return self.get_weekly_track_chart()
@LastfmBase.cachedProperty
def weeklyTrackChartList(self):
wcl = list(self.weeklyChartList)
def weekly_track_chart_list(self):
wcl = list(self.weekly_chart_list)
wcl.reverse()
@lazylist
def gen(lst):
for wc in wcl:
yield self.getWeeklyTrackChart(wc.start, wc.end)
yield self.get_weekly_track_chart(wc.start, wc.end)
return gen()
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['name'])
except KeyError:
raise LastfmInvalidParametersError("name has to be provided for hashing")
raise InvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
return self.__class__.hash_func(name = self.name)
def __eq__(self, other):
return self.name == other.name
@ -116,5 +116,5 @@ class Group(LastfmBase):
return "<lastfm.Group: %s>" % self.name
from api import Api
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from weeklychart import WeeklyChart, WeeklyAlbumChart, WeeklyArtistChart, WeeklyTrackChart

View File

@ -18,7 +18,7 @@ class Playlist(LastfmBase):
"""playlist's data"""
params = {'method': 'playlist.fetch', 'playlistURL': self.__url}
tmp = StringIO.StringIO()
ElementTree.ElementTree(self.__api._fetchData(params)[0]).write(tmp)
ElementTree.ElementTree(self.__api._fetch_data(params)[0]).write(tmp)
return tmp.getvalue()
@property
@ -31,14 +31,14 @@ class Playlist(LastfmBase):
return Playlist(api, url = url)
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['url'])
except KeyError:
raise LastfmInvalidParametersError("url has to be provided for hashing")
raise InvalidParametersError("url has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(url = self.url)
return self.__class__.hash_func(url = self.url)
def __eq__(self, other):
return self.url == other.url
@ -51,7 +51,7 @@ class Playlist(LastfmBase):
import StringIO
import platform
from error import LastfmInvalidParametersError
from error import InvalidParametersError
python_version = platform.python_version_tuple()
if python_version[0] == 2 and python_version[1] >= 5:
@ -63,5 +63,5 @@ else:
try:
import ElementTree
except ImportError:
from error import LastfmError
raise LastfmError("Install ElementTree package for using python-lastfm")
from error import Error
raise Error("Install ElementTree package for using python-lastfm")

View File

@ -7,7 +7,7 @@ __license__ = "GNU Lesser General Public License"
from album import Album
from artist import Artist
from base import LastfmBase
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from event import Event
from geo import Location, Country
from group import Group
@ -24,7 +24,7 @@ class Registry(object):
def __getitem__(self, name):
if name not in Registry.keys:
raise LastfmInvalidParametersError("Key does not correspond to a valid class")
raise InvalidParametersError("Key does not correspond to a valid class")
else:
try:
vals = LastfmBase.registry[eval(name)].values()

View File

@ -9,14 +9,14 @@ class Searchable(object):
@classmethod
def search(cls,
api,
searchItem,
search_item,
limit = None,
**kwds):
from api import Api
clsName = cls.__name__.lower()
cls_name = cls.__name__.lower()
params = {
'method': '%s.search'%clsName,
clsName: searchItem
'method': '%s.search'%cls_name,
cls_name: search_item
}
for kwd in kwds:
if kwds[kwd] is not None:
@ -27,21 +27,25 @@ class Searchable(object):
@lazylist
def gen(lst):
data = api._fetchData(params).find('results')
data = api._fetch_data(params).find('results')
totalPages = int(data.findtext("{%s}totalResults" % Api.SEARCH_XMLNS))/ \
int(data.findtext("{%s}itemsPerPage" % Api.SEARCH_XMLNS)) + 1
@lazylist
def gen2(lst, data):
for a in data.findall('%smatches/%s'%(clsName, clsName)):
yield cls._searchYieldFunc(api, a)
for a in data.findall('%smatches/%s'%(cls_name, cls_name)):
yield cls._search_yield_func(api, a)
for a in gen2(data):
yield a
for page in xrange(2, totalPages+1):
params.update({'page': page})
data = api._fetchData(params).find('results')
data = api._fetch_data(params).find('results')
for a in gen2(data):
yield a
return gen()
return gen()
@staticmethod
def _search_yield_func(api, search_term):
pass

View File

@ -10,7 +10,7 @@ class Sharable(object):
def share(self, recipient, message = None):
from user import User
params = self._defaultParams({'method': '%s.share' % self.__class__.__name__.lower()})
params = self._default_params({'method': '%s.share' % self.__class__.__name__.lower()})
if message is not None:
params['message'] = message
@ -21,4 +21,4 @@ class Sharable(object):
if isinstance(recipient[i], User):
recipient[i] = recipient[i].name
params['recipient'] = ",".join(recipient)
self.__api._postData(params)
self.__api._post_data(params)

View File

@ -17,7 +17,7 @@ class Tag(LastfmBase, Searchable):
streamable = None,
stats = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
self.__url = url
@ -50,7 +50,7 @@ class Tag(LastfmBase, Searchable):
def similar(self):
"""tags similar to this tag"""
params = {'method': 'tag.getSimilar', 'tag': self.name}
data = self.__api._fetchData(params).find('similartags')
data = self.__api._fetch_data(params).find('similartags')
return [
Tag(
self.__api,
@ -63,15 +63,15 @@ class Tag(LastfmBase, Searchable):
]
@LastfmBase.topProperty("similar")
def mostSimilar(self):
def most_similar(self):
"""most similar tag to this tag"""
pass
@LastfmBase.cachedProperty
def topAlbums(self):
def top_albums(self):
"""top albums for the tag"""
params = {'method': 'tag.getTopAlbums', 'tag': self.name}
data = self.__api._fetchData(params).find('topalbums')
data = self.__api._fetch_data(params).find('topalbums')
return [
Album(
self.__api,
@ -96,16 +96,16 @@ class Tag(LastfmBase, Searchable):
for a in data.findall('album')
]
@LastfmBase.topProperty("topAlbums")
def topAlbum(self):
@LastfmBase.topProperty("top_albums")
def top_album(self):
"""top album for the tag"""
pass
@LastfmBase.cachedProperty
def topArtists(self):
def top_artists(self):
"""top artists for the tag"""
params = {'method': 'tag.getTopArtists', 'tag': self.name}
data = self.__api._fetchData(params).find('topartists')
data = self.__api._fetch_data(params).find('topartists')
return [
Artist(
self.__api,
@ -124,16 +124,16 @@ class Tag(LastfmBase, Searchable):
for a in data.findall('artist')
]
@LastfmBase.topProperty("topArtists")
def topArtist(self):
@LastfmBase.topProperty("top_artists")
def top_artist(self):
"""top artist for the tag"""
pass
@LastfmBase.cachedProperty
def topTracks(self):
def top_tracks(self):
"""top tracks for the tag"""
params = {'method': 'tag.getTopTracks', 'tag': self.name}
data = self.__api._fetchData(params).find('toptracks')
data = self.__api._fetch_data(params).find('toptracks')
return [
Track(
self.__api,
@ -159,8 +159,8 @@ class Tag(LastfmBase, Searchable):
for t in data.findall('track')
]
@LastfmBase.topProperty("topTracks")
def topTrack(self):
@LastfmBase.topProperty("top_tracks")
def top_track(self):
"""top track for the tag"""
pass
@ -170,9 +170,9 @@ class Tag(LastfmBase, Searchable):
"lastfm://playlist/tag/%s/freetracks" % self.name)
@staticmethod
def getTopTags(api):
def get_top_tags(api):
params = {'method': 'tag.getTopTags'}
data = api._fetchData(params).find('toptags')
data = api._fetch_data(params).find('toptags')
return [
Tag(
api,
@ -187,7 +187,7 @@ class Tag(LastfmBase, Searchable):
]
@staticmethod
def _searchYieldFunc(api, tag):
def _search_yield_func(api, tag):
return Tag(
api,
name = tag.findtext('name'),
@ -199,14 +199,14 @@ class Tag(LastfmBase, Searchable):
)
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['name'])
except KeyError:
raise LastfmInvalidParametersError("name has to be provided for hashing")
raise InvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
return self.__class__.hash_func(name = self.name)
def __eq__(self, other):
return self.name == other.name
@ -220,7 +220,7 @@ class Tag(LastfmBase, Searchable):
from album import Album
from api import Api
from artist import Artist
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from playlist import Playlist
from stats import Stats
from track import Track

View File

@ -14,8 +14,8 @@ class Taggable(object):
@LastfmBase.cachedProperty
def tags(self):
from tag import Tag
params = self._defaultParams({'method': '%s.getTags' % self.__class__.__name__.lower()})
data = self.__api._fetchData(params, sign = True, session = True, no_cache = True).find('tags')
params = self._default_params({'method': '%s.getTags' % self.__class__.__name__.lower()})
data = self.__api._fetch_data(params, sign = True, session = True, no_cache = True).find('tags')
return SafeList([
Tag(
self.__api,
@ -24,14 +24,14 @@ class Taggable(object):
)
for t in data.findall('tag')
],
self.addTags, self.removeTag)
self.add_tags, self.remove_tag)
def addTags(self, tags):
def add_tags(self, tags):
from tag import Tag
while(len(tags) > 10):
section = tags[0:9]
tags = tags[9:]
self.addTags(section)
self.add_tags(section)
if len(tags) == 0: return
@ -42,21 +42,24 @@ class Taggable(object):
elif isinstance(tag, str):
tagnames.append(tag)
params = self._defaultParams({
params = self._default_params({
'method': '%s.addTags' % self.__class__.__name__.lower(),
'tags': ",".join(tagnames)
})
self.__api._postData(params)
self.__api._post_data(params)
self.__tags = None
def removeTag(self, tag):
def remove_tag(self, tag):
from tag import Tag
if isinstance(tag, Tag):
tag = tag.name
params = self._defaultParams({
params = self._default_params({
'method': '%s.removeTag' % self.__class__.__name__.lower(),
'tag': tag
})
self.__api._postData(params)
self.__tags = None
self.__api._post_data(params)
self.__tags = None
def _default_params(self, extra_params):
pass

View File

@ -43,7 +43,7 @@ class Tasteometer(object):
}
if limit is not None:
params.update({'limit': limit})
data = api._fetchData(params).find('comparison/result')
data = api._fetch_data(params).find('comparison/result')
return Tasteometer(
score = float(data.findtext('score')),
matches = int(data.find('artists').attrib['matches']),

View File

@ -19,17 +19,17 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
url = None,
duration = None,
streamable = None,
fullTrack = None,
full_track = None,
artist = None,
album = None,
position = None,
image = None,
stats = None,
playedOn = None,
lovedOn = None,
played_on = None,
loved_on = None,
wiki = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
Taggable.init(self, api)
Sharable.init(self, api)
self.__api = api
@ -39,7 +39,7 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
self.__url = url
self.__duration = duration
self.__streamable = streamable
self.__fullTrack = fullTrack
self.__full_track = full_track
self.__artist = artist
self.__album = album
self.__position = position
@ -51,8 +51,8 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
rank = stats.rank,
listeners = stats.listeners,
)
self.__playedOn = playedOn
self.__lovedOn = lovedOn
self.__played_on = played_on
self.__loved_on = loved_on
self.__wiki = wiki and Wiki(
subject = self,
published = wiki.published,
@ -89,15 +89,15 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
def streamable(self):
"""is the track streamable"""
if self.__streamable is None:
self._fillInfo()
self._fill_info()
return self.__streamable
@property
def fullTrack(self):
def full_track(self):
"""is the full track streamable"""
if self.__fullTrack is None:
self._fillInfo()
return self.__fullTrack
if self.__full_track is None:
self._fill_info()
return self.__full_track
@property
def artist(self):
@ -108,14 +108,14 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
def album(self):
"""artist of the track"""
if self.__album is None:
self._fillInfo()
self._fill_info()
return self.__album
@property
def position(self):
"""position of the track"""
if self.__position is None:
self._fillInfo()
self._fill_info()
return self.__position
@property
@ -131,12 +131,12 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
@property
def playedOn(self):
"""datetime the track was last played"""
return self.__playedOn
return self.__played_on
@property
def lovedOn(self):
"""datetime the track was marked 'loved'"""
return self.__lovedOn
return self.__loved_on
@property
def wiki(self):
@ -144,27 +144,27 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
if self.__wiki == "na":
return None
if self.__wiki is None:
self._fillInfo()
self._fill_info()
return self.__wiki
def _defaultParams(self, extraParams = None):
def _default_params(self, extra_params = None):
if not (self.artist and self.name):
raise LastfmInvalidParametersError("artist and track have to be provided.")
raise InvalidParametersError("artist and track have to be provided.")
params = {'artist': self.artist.name, 'track': self.name}
if extraParams is not None:
params.update(extraParams)
if extra_params is not None:
params.update(extra_params)
return params
@LastfmBase.cachedProperty
def similar(self):
"""tracks similar to this track"""
params = Track._checkParams(
params = Track._check_params(
{'method': 'track.getSimilar'},
self.artist.name,
self.name,
self.mbid
)
data = self.__api._fetchData(params).find('similartracks')
data = self.__api._fetch_data(params).find('similartracks')
return [
Track(
self.__api,
@ -190,20 +190,20 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
]
@LastfmBase.topProperty("similar")
def mostSimilar(self):
def most_similar(self):
"""track most similar to this track"""
pass
@LastfmBase.cachedProperty
def topFans(self):
def top_fans(self):
"""top fans of the track"""
params = Track._checkParams(
params = Track._check_params(
{'method': 'track.getTopFans'},
self.artist.name,
self.name,
self.mbid
)
data = self.__api._fetchData(params).find('topfans')
data = self.__api._fetch_data(params).find('topfans')
return [
User(
self.__api,
@ -219,21 +219,21 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
for u in data.findall('user')
]
@LastfmBase.topProperty("topFans")
def topFan(self):
@LastfmBase.topProperty("top_fans")
def top_fan(self):
"""topmost fan of the track"""
pass
@LastfmBase.cachedProperty
def topTags(self):
def top_tags(self):
"""top tags for the track"""
params = Track._checkParams(
params = Track._check_params(
{'method': 'track.getTopTags'},
self.artist.name,
self.name,
self.mbid
)
data = self.__api._fetchData(params).find('toptags')
data = self.__api._fetch_data(params).find('toptags')
return [
Tag(
self.__api,
@ -248,21 +248,21 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
for t in data.findall('tag')
]
@LastfmBase.topProperty("topTags")
def topTag(self):
@LastfmBase.topProperty("top_tags")
def top_tag(self):
"""topmost tag for the track"""
pass
def love(self):
params = self._defaultParams({'method': 'track.love'})
self.__api._postData(params)
params = self._default_params({'method': 'track.love'})
self.__api._post_data(params)
def ban(self):
params = self._defaultParams({'method': 'track.ban'})
self.__api._postData(params)
params = self._default_params({'method': 'track.ban'})
self.__api._post_data(params)
@staticmethod
def _searchYieldFunc(api, track):
def _search_yield_func(api, track):
return Track(
api,
name = track.findtext('name'),
@ -281,21 +281,21 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
)
@staticmethod
def _fetchData(api,
def _fetch_data(api,
artist = None,
track = None,
mbid = None):
params = Track._checkParams({'method': 'track.getInfo'}, artist, track, mbid)
return api._fetchData(params).find('track')
params = Track._check_params({'method': 'track.getInfo'}, artist, track, mbid)
return api._fetch_data(params).find('track')
def _fillInfo(self):
data = Track._fetchData(self.__api, self.artist.name, self.name)
def _fill_info(self):
data = Track._fetch_data(self.__api, self.artist.name, self.name)
self.__id = int(data.findtext('id'))
self.__mbid = data.findtext('mbid')
self.__url = data.findtext('url')
self.__duration = int(data.findtext('duration'))
self.__streamable = (data.findtext('streamable') == '1'),
self.__fullTrack = (data.find('streamable').attrib['fulltrack'] == '1'),
self.__full_track = (data.find('streamable').attrib['fulltrack'] == '1'),
self.__image = dict([(i.get('size'), i.text) for i in data.findall('image')])
self.__stats = Stats(
@ -332,11 +332,11 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
self.__wiki = 'na'
@staticmethod
def getInfo(api,
def get_info(api,
artist = None,
track = None,
mbid = None):
data = Track._fetchData(api, artist, track, mbid)
data = Track._fetch_data(api, artist, track, mbid)
t = Track(
api,
name = data.findtext('name'),
@ -345,16 +345,16 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
name = data.findtext('artist/name'),
),
)
t._fillInfo()
t._fill_info()
return t
@staticmethod
def _checkParams(params,
def _check_params(params,
artist = None,
track = None,
mbid = None):
if not ((artist and track) or mbid):
raise LastfmInvalidParametersError("either (artist and track) or mbid has to be given as argument.")
raise InvalidParametersError("either (artist and track) or mbid has to be given as argument.")
if artist and track:
params.update({'artist': artist, 'track': track})
@ -363,14 +363,14 @@ class Track(LastfmBase, Taggable, Sharable, Searchable):
return params
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash("%s%s" % (kwds['name'], hash(kwds['artist'])))
except KeyError:
raise LastfmInvalidParametersError("name and artist have to be provided for hashing")
raise InvalidParametersError("name and artist have to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name, artist = self.artist)
return self.__class__.hash_func(name = self.name, artist = self.artist)
def __eq__(self, other):
if self.mbid and other.mbid:
@ -393,7 +393,7 @@ from datetime import datetime
from api import Api
from artist import Artist
from album import Album
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from stats import Stats
from tag import Tag
from user import User

View File

@ -22,7 +22,7 @@ class User(LastfmBase):
gender = None,
subscriber = None):
if not isinstance(api, Api):
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
raise InvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
self.__url = url
@ -88,14 +88,14 @@ class User(LastfmBase):
@LastfmBase.cachedProperty
def events(self):
params = {'method': 'user.getEvents', 'user': self.name}
data = self.__api._fetchData(params).find('events')
data = self.__api._fetch_data(params).find('events')
return [
Event.createFromData(self.__api, e)
Event.create_from_data(self.__api, e)
for e in data.findall('event')
]
def getPastEvents(self,
def get_past_events(self,
limit = None):
params = {'method': 'user.getPastEvents', 'user': self.name}
if limit is not None:
@ -103,34 +103,34 @@ class User(LastfmBase):
@lazylist
def gen(lst):
data = self.__api._fetchData(params).find('events')
data = self.__api._fetch_data(params).find('events')
totalPages = int(data.attrib['totalPages'])
@lazylist
def gen2(lst, data):
for e in data.findall('event'):
yield Event.createFromData(self.__api, e)
yield Event.create_from_data(self.__api, e)
for e in gen2(data):
yield e
for page in xrange(2, totalPages+1):
params.update({'page': page})
data = self.__api._fetchData(params).find('events')
data = self.__api._fetch_data(params).find('events')
for e in gen2(data):
yield e
return gen()
@LastfmBase.cachedProperty
def pastEvents(self):
return self.getPastEvents()
def past_events(self):
return self.get_past_events()
def getFriends(self,
def get_friends(self,
limit = None):
params = {'method': 'user.getFriends', 'user': self.name}
if limit is not None:
params.update({'limit': limit})
data = self.__api._fetchData(params).find('friends')
data = self.__api._fetch_data(params).find('friends')
return [
User(
self.__api,
@ -146,13 +146,13 @@ class User(LastfmBase):
@LastfmBase.cachedProperty
def friends(self):
"""friends of the user"""
return self.getFriends()
return self.get_friends()
def getNeighbours(self, limit = None):
def get_neighbours(self, limit = None):
params = {'method': 'user.getNeighbours', 'user': self.name}
if limit is not None:
params.update({'limit': limit})
data = self.__api._fetchData(params).find('neighbours')
data = self.__api._fetch_data(params).find('neighbours')
return [
User(
self.__api,
@ -171,10 +171,10 @@ class User(LastfmBase):
@LastfmBase.cachedProperty
def neighbours(self):
"""neighbours of the user"""
return self.getNeighbours()
return self.get_neighbours()
@LastfmBase.topProperty("neighbours")
def nearestNeighbour(self):
def nearest_neighbour(self):
"""nearest neightbour of the user"""
pass
@ -182,7 +182,7 @@ class User(LastfmBase):
def playlists(self):
"""playlists of the user"""
params = {'method': 'user.getPlaylists', 'user': self.name}
data = self.__api._fetchData(params).find('playlists')
data = self.__api._fetch_data(params).find('playlists')
return [
User.Playlist(
self.__api,
@ -201,9 +201,9 @@ class User(LastfmBase):
]
@LastfmBase.cachedProperty
def lovedTracks(self):
def loved_tracks(self):
params = {'method': 'user.getLovedTracks', 'user': self.name}
data = self.__api._fetchData(params).find('lovedtracks')
data = self.__api._fetch_data(params).find('lovedtracks')
return [
Track(
self.__api,
@ -228,9 +228,9 @@ class User(LastfmBase):
for t in data.findall('track')
]
def getRecentTracks(self, limit = None):
def get_recent_tracks(self, limit = None):
params = {'method': 'user.getRecentTracks', 'user': self.name}
data = self.__api._fetchData(params, no_cache = True).find('recenttracks')
data = self.__api._fetch_data(params, no_cache = True).find('recenttracks')
return [
Track(
self.__api,
@ -269,20 +269,20 @@ class User(LastfmBase):
]
@property
def recentTracks(self):
def recent_tracks(self):
"""recent tracks played by the user"""
return self.getRecentTracks()
return self.get_recent_tracks()
@LastfmBase.topProperty("recentTracks")
def mostRecentTrack(self):
@LastfmBase.topProperty("recent_tracks")
def most_recent_track(self):
"""most recent track played by the user"""
pass
def getTopAlbums(self, period = None):
def get_top_albums(self, period = None):
params = {'method': 'user.getTopAlbums', 'user': self.name}
if period is not None:
params.update({'period': period})
data = self.__api._fetchData(params).find('topalbums')
data = self.__api._fetch_data(params).find('topalbums')
return [
Album(
@ -309,20 +309,20 @@ class User(LastfmBase):
]
@LastfmBase.cachedProperty
def topAlbums(self):
def top_albums(self):
"""overall top albums of the user"""
return self.getTopAlbums()
return self.get_top_albums()
@LastfmBase.topProperty("topAlbums")
def topAlbum(self):
@LastfmBase.topProperty("top_albums")
def top_album(self):
"""overall top most album of the user"""
pass
def getTopArtists(self, period = None):
def get_top_artists(self, period = None):
params = {'method': 'user.getTopArtists', 'user': self.name}
if period is not None:
params.update({'period': period})
data = self.__api._fetchData(params).find('topartists')
data = self.__api._fetch_data(params).find('topartists')
return [
Artist(
@ -343,20 +343,20 @@ class User(LastfmBase):
]
@LastfmBase.cachedProperty
def topArtists(self):
def top_artists(self):
"""top artists of the user"""
return self.getTopArtists()
return self.get_top_artists()
@LastfmBase.topProperty("topArtists")
def topArtist(self):
@LastfmBase.topProperty("top_artists")
def top_artist(self):
"""top artist of the user"""
pass
def getTopTracks(self, period = None):
def get_top_tracks(self, period = None):
params = {'method': 'user.getTopTracks', 'user': self.name}
if period is not None:
params.update({'period': period})
data = self.__api._fetchData(params).find('toptracks')
data = self.__api._fetch_data(params).find('toptracks')
return [
Track(
self.__api,
@ -383,20 +383,20 @@ class User(LastfmBase):
]
@LastfmBase.cachedProperty
def topTracks(self):
def top_tracks(self):
"""top tracks of the user"""
return self.getTopTracks()
return self.get_top_tracks()
@LastfmBase.topProperty("topTracks")
def topTrack(self):
@LastfmBase.topProperty("top_tracks")
def top_track(self):
"""top track of the user"""
return (len(self.topTracks) and self.topTracks[0] or None)
return (len(self.top_tracks) and self.top_tracks[0] or None)
def getTopTags(self, limit = None):
def get_top_tags(self, limit = None):
params = {'method': 'user.getTopTags', 'user': self.name}
if limit is not None:
params.update({'limit': limit})
data = self.__api._fetchData(params).find('toptags')
data = self.__api._fetch_data(params).find('toptags')
return [
Tag(
self.__api,
@ -412,96 +412,96 @@ class User(LastfmBase):
]
@LastfmBase.cachedProperty
def topTags(self):
def top_tags(self):
"""top tags of the user"""
return self.getTopTags()
return self.get_top_tags()
@LastfmBase.topProperty("topTags")
def topTag(self):
@LastfmBase.topProperty("top_tags")
def top_tag(self):
"""top tag of the user"""
pass
@LastfmBase.cachedProperty
def weeklyChartList(self):
def weekly_chart_list(self):
params = {'method': 'user.getWeeklyChartList', 'user': self.name}
data = self.__api._fetchData(params).find('weeklychartlist')
data = self.__api._fetch_data(params).find('weeklychartlist')
return [
WeeklyChart.createFromData(self.__api, self, c)
WeeklyChart.create_from_data(self.__api, self, c)
for c in data.findall('chart')
]
def getWeeklyAlbumChart(self,
def get_weekly_album_chart(self,
start = None,
end = None):
params = {'method': 'user.getWeeklyAlbumChart', 'user': self.name}
params = WeeklyChart._checkWeeklyChartParams(params, start, end)
data = self.__api._fetchData(params).find('weeklyalbumchart')
return WeeklyAlbumChart.createFromData(self.__api, self, data)
params = WeeklyChart._check_weekly_chart_params(params, start, end)
data = self.__api._fetch_data(params).find('weeklyalbumchart')
return WeeklyAlbumChart.create_from_data(self.__api, self, data)
@LastfmBase.cachedProperty
def recentWeeklyAlbumChart(self):
return self.getWeeklyAlbumChart()
def recent_weekly_album_chart(self):
return self.get_weekly_album_chart()
@LastfmBase.cachedProperty
def weeklyAlbumChartList(self):
wcl = list(self.weeklyChartList)
def weekly_album_chart_list(self):
wcl = list(self.weekly_chart_list)
wcl.reverse()
@lazylist
def gen(lst):
for wc in wcl:
try:
yield self.getWeeklyAlbumChart(wc.start, wc.end)
except LastfmError:
yield self.get_weekly_album_chart(wc.start, wc.end)
except Error:
pass
return gen()
def getWeeklyArtistChart(self,
def get_weekly_artist_chart(self,
start = None,
end = None):
params = {'method': 'user.getWeeklyArtistChart', 'user': self.name}
params = WeeklyChart._checkWeeklyChartParams(params, start, end)
data = self.__api._fetchData(params).find('weeklyartistchart')
return WeeklyArtistChart.createFromData(self.__api, self, data)
params = WeeklyChart._check_weekly_chart_params(params, start, end)
data = self.__api._fetch_data(params).find('weeklyartistchart')
return WeeklyArtistChart.create_from_data(self.__api, self, data)
@LastfmBase.cachedProperty
def recentWeeklyArtistChart(self):
return self.getWeeklyArtistChart()
def recent_weekly_artist_chart(self):
return self.get_weekly_artist_chart()
@LastfmBase.cachedProperty
def weeklyArtistChartList(self):
wcl = list(self.weeklyChartList)
def weekly_artist_chart_list(self):
wcl = list(self.weekly_chart_list)
wcl.reverse()
@lazylist
def gen(lst):
for wc in wcl:
try:
yield self.getWeeklyArtistChart(wc.start, wc.end)
except LastfmError:
yield self.get_weekly_artist_chart(wc.start, wc.end)
except Error:
pass
return gen()
def getWeeklyTrackChart(self,
def get_weekly_track_chart(self,
start = None,
end = None):
params = {'method': 'user.getWeeklyTrackChart', 'user': self.name}
params = WeeklyChart._checkWeeklyChartParams(params, start, end)
data = self.__api._fetchData(params).find('weeklytrackchart')
return WeeklyTrackChart.createFromData(self.__api, self, data)
params = WeeklyChart._check_weekly_chart_params(params, start, end)
data = self.__api._fetch_data(params).find('weeklytrackchart')
return WeeklyTrackChart.create_from_data(self.__api, self, data)
@LastfmBase.cachedProperty
def recentWeeklyTrackChart(self):
return self.getWeeklyTrackChart()
def recent_weekly_track_chart(self):
return self.get_weekly_track_chart()
@LastfmBase.cachedProperty
def weeklyTrackChartList(self):
wcl = list(self.weeklyChartList)
def weekly_track_chart_list(self):
wcl = list(self.weekly_chart_list)
wcl.reverse()
@lazylist
def gen(lst):
for wc in wcl:
try:
yield self.getWeeklyTrackChart(wc.start, wc.end)
except LastfmError:
yield self.get_weekly_track_chart(wc.start, wc.end)
except Error:
pass
return gen()
@ -515,8 +515,8 @@ class User(LastfmBase):
return self.__library
@staticmethod
def getAuthenticatedUser(api):
data = api._fetchData({'method': 'user.getInfo'}, sign = True, session = True).find('user')
def get_authenticated_user(api):
data = api._fetch_data({'method': 'user.getInfo'}, sign = True, session = True).find('user')
return User(
api,
name = data.findtext('name'),
@ -533,14 +533,14 @@ class User(LastfmBase):
)
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['name'])
except KeyError:
raise LastfmInvalidParametersError("name has to be provided for hashing")
raise InvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
return self.__class__.hash_func(name = self.name)
def __eq__(self, other):
return self.name == other.name
@ -584,21 +584,21 @@ class User(LastfmBase):
def addTrack(self, track):
params = {'method': 'playlist.addTrack', 'playlistID': self.id}
if not isinstance(track, Track):
track = self.__api.searchTrack(track)[0]
track = self.__api.search_track(track)[0]
params['artist'] = track.artist.name
params['track'] = track.name
self.__api._postData(params)
self.__api._post_data(params)
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['id'])
except KeyError:
raise LastfmInvalidParametersError("id has to be provided for hashing")
raise InvalidParametersError("id has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(id = self.id)
return self.__class__.hash_func(id = self.id)
def __repr__(self):
return "<lastfm.User.Playlist: %s>" % self.title
@ -613,7 +613,7 @@ class User(LastfmBase):
def user(self):
return self.__user
def getAlbums(self,
def get_albums(self,
limit = None):
params = {'method': 'library.getAlbums', 'user': self.user.name}
if limit is not None:
@ -621,8 +621,8 @@ class User(LastfmBase):
@lazylist
def gen(lst):
data = self.__api._fetchData(params).find('albums')
totalPages = int(data.attrib['totalPages'])
data = self.__api._fetch_data(params).find('albums')
total_pages = int(data.attrib['totalPages'])
@lazylist
def gen2(lst, data):
@ -651,11 +651,11 @@ class User(LastfmBase):
for a in gen2(data):
yield a
for page in xrange(2, totalPages+1):
for page in xrange(2, total_pages+1):
params.update({'page': page})
try:
data = self.__api._fetchData(params).find('albums')
except LastfmError:
data = self.__api._fetch_data(params).find('albums')
except Error:
continue
for a in gen2(data):
yield a
@ -663,9 +663,9 @@ class User(LastfmBase):
@LastfmBase.cachedProperty
def albums(self):
return self.getAlbums()
return self.get_albums()
def getArtists(self,
def get_artists(self,
limit = None):
params = {'method': 'library.getArtists', 'user': self.user.name}
if limit is not None:
@ -673,8 +673,8 @@ class User(LastfmBase):
@lazylist
def gen(lst):
data = self.__api._fetchData(params).find('artists')
totalPages = int(data.attrib['totalPages'])
data = self.__api._fetch_data(params).find('artists')
total_pages = int(data.attrib['totalPages'])
@lazylist
def gen2(lst, data):
@ -697,11 +697,11 @@ class User(LastfmBase):
for a in gen2(data):
yield a
for page in xrange(2, totalPages+1):
for page in xrange(2, total_pages+1):
params.update({'page': page})
try:
data = self.__api._fetchData(params).find('artists')
except LastfmError:
data = self.__api._fetch_data(params).find('artists')
except Error:
continue
for a in gen2(data):
yield a
@ -709,9 +709,9 @@ class User(LastfmBase):
@LastfmBase.cachedProperty
def artists(self):
return self.getArtists()
return self.get_artists()
def getTracks(self,
def get_tracks(self,
limit = None):
params = {'method': 'library.getTracks', 'user': self.user.name}
if limit is not None:
@ -719,7 +719,7 @@ class User(LastfmBase):
@lazylist
def gen(lst):
data = self.__api._fetchData(params).find('tracks')
data = self.__api._fetch_data(params).find('tracks')
totalPages = int(data.attrib['totalPages'])
@lazylist
@ -754,8 +754,8 @@ class User(LastfmBase):
params.update({'page': page})
data = None
try:
data = self.__api._fetchData(params).find('tracks')
except LastfmError:
data = self.__api._fetch_data(params).find('tracks')
except Error:
continue
for t in gen2(data):
yield t
@ -763,17 +763,17 @@ class User(LastfmBase):
@LastfmBase.cachedProperty
def tracks(self):
return self.getTracks()
return self.get_tracks()
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash(kwds['user'])
except KeyError:
raise LastfmInvalidParametersError("user has to be provided for hashing")
raise InvalidParametersError("user has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(user = self.user)
return self.__class__.hash_func(user = self.user)
def __repr__(self):
return "<lastfm.User.Library: for user '%s'>" % self.user.name
@ -784,7 +784,7 @@ import time
from api import Api
from artist import Artist
from album import Album
from error import LastfmError, LastfmInvalidParametersError
from error import Error, InvalidParametersError
from event import Event
from geo import Country
from stats import Stats

View File

@ -33,7 +33,7 @@ class WeeklyChart(LastfmBase):
return self.__stats
@staticmethod
def createFromData(api, subject, data):
def create_from_data(api, subject, data):
return WeeklyChart(
subject = subject,
start = datetime.utcfromtimestamp(int(data.attrib['from'])),
@ -41,9 +41,9 @@ class WeeklyChart(LastfmBase):
)
@staticmethod
def _checkWeeklyChartParams(params, start = None, end = None):
def _check_weekly_chart_params(params, start = None, end = None):
if (start is not None and end is None) or (start is None and end is not None):
raise LastfmInvalidParametersError("both start and end have to be provided.")
raise InvalidParametersError("both start and end have to be provided.")
if start is not None and end is not None:
if isinstance(start, datetime) and isinstance(end, datetime):
params.update({
@ -51,12 +51,12 @@ class WeeklyChart(LastfmBase):
'to': int(calendar.timegm(end.timetuple()))
})
else:
raise LastfmInvalidParametersError("start and end must be datetime.datetime instances")
raise InvalidParametersError("start and end must be datetime.datetime instances")
return params
@staticmethod
def hashFunc(*args, **kwds):
def hash_func(*args, **kwds):
try:
return hash("%s%s%s%s" % (
kwds['subject'].__class__.__name__,
@ -65,10 +65,10 @@ class WeeklyChart(LastfmBase):
kwds['end']
))
except KeyError:
raise LastfmInvalidParametersError("subject, start and end have to be provided for hashing")
raise InvalidParametersError("subject, start and end have to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(
return self.__class__.hash_func(
subject = self.subject,
start = self.start,
end = self.end
@ -109,7 +109,7 @@ class WeeklyAlbumChart(WeeklyChart):
return self.__albums
@staticmethod
def createFromData(api, subject, data):
def create_from_data(api, subject, data):
w = WeeklyChart(
subject = subject,
start = datetime.utcfromtimestamp(int(data.attrib['from'])),
@ -163,7 +163,7 @@ class WeeklyArtistChart(WeeklyChart):
return self.__artists
@staticmethod
def createFromData(api, subject, data):
def create_from_data(api, subject, data):
w = WeeklyChart(
subject = subject,
start = datetime.utcfromtimestamp(int(data.attrib['from'])),
@ -211,7 +211,7 @@ class WeeklyTrackChart(WeeklyChart):
return self.__tracks
@staticmethod
def createFromData(api, subject, data):
def create_from_data(api, subject, data):
w = WeeklyChart(
subject = subject,
start = datetime.utcfromtimestamp(int(data.attrib['from'])),
@ -258,6 +258,6 @@ import calendar
from album import Album
from artist import Artist
from error import LastfmInvalidParametersError
from error import InvalidParametersError
from stats import Stats
from track import Track