resolved issue 1 by subclassing LastfmError class and replacing the errors raised in code by the appropriate ones.

master
Abhinav Sarkar 2008-08-30 20:37:49 +00:00
parent 9795b1f18f
commit a2320e6dd0
13 changed files with 146 additions and 76 deletions

View File

@ -20,7 +20,7 @@ class Album(LastfmBase):
stats = None,
topTags = None):
if not isinstance(api, Api):
raise LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
self.__artist = artist
@ -105,7 +105,7 @@ class Album(LastfmBase):
subject = self,
name = t.findtext('name'),
url = t.findtext('url')
)
)
for t in data.findall('toptags/tag')
]
@ -121,7 +121,7 @@ class Album(LastfmBase):
mbid = None):
params = {'method': 'album.getinfo'}
if not ((artist and album) or mbid):
raise LastfmError("either (artist and album) or mbid has to be given as argument.")
raise LastfmInvalidParametersError("either (artist and album) or mbid has to be given as argument.")
if artist and album:
params.update({'artist': artist, 'album': album})
elif mbid:
@ -162,7 +162,6 @@ class Album(LastfmBase):
name = data.findtext('name'),
artist = Artist(
api,
subject = self,
name = data.findtext('artist'),
),
)
@ -175,7 +174,7 @@ class Album(LastfmBase):
try:
return hash("%s%s" % (kwds['name'], hash(kwds['artist'])))
except KeyError:
raise LastfmError("name and artist have to be provided for hashing")
raise LastfmInvalidParametersError("name and artist have to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name, artist = self.artist)
@ -203,6 +202,6 @@ import time
from api import Api
from artist import Artist
from error import LastfmError
from error import LastfmInvalidParametersError
from stats import Stats
from tag import Tag

View File

@ -6,7 +6,7 @@ __license__ = "GNU Lesser General Public License"
class Api(object):
"""The class representing the last.fm web services API."""
DEFAULT_CACHE_TIMEOUT = 3600 # cache for 1 hour
API_ROOT_URL = "http://ws.audioscrobbler.com/2.0/"
FETCH_INTERVAL = 1
@ -31,7 +31,7 @@ class Api(object):
def getApiKey(self):
return self.__apiKey
def setCache(self, cache):
'''Override the default cache. Set to None to prevent caching.
@ -127,7 +127,7 @@ class Api(object):
return None
else:
return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None]))
def getAlbum(self,
artist = None,
album = None,
@ -135,57 +135,57 @@ class Api(object):
if isinstance(artist, Artist):
artist = artist.name
return Album.getInfo(self, artist, album, mbid)
def getArtist(self,
artist = None,
mbid = None):
return Artist.getInfo(self, artist, mbid)
def searchArtist(self,
artist,
limit = None):
return Artist.search(self, artist, limit)
def getEvent(self, event):
return Event.getInfo(self, event)
def getLocation(self, name):
return Location(self, name = name)
def getCountry(self, name):
return Country(self, name = name)
def getGroup(self, name):
return Group(self, name = name)
def fetchPlaylist(self, url):
return Playlist.fetch(self, url)
def getTag(self, name):
return Tag(self, name = name)
def getGlobalTopTags(self):
return Tag.getTopTags(self)
def searchTag(self,
tag,
limit = None):
return Tag.search(self, tag, limit)
def compareTaste(self,
type1, type2,
value1, value2,
limit = None):
return Tasteometer.compare(self, type1, type2, value1, value2, limit)
def getTrack(self, track, artist):
if isinstance(artist, Artist):
artist = artist.name
result = Track.search(self, track, artist)
if len(result.matches) == 0:
raise LastfmError("'%s' by %s: no such track found" % (track, artist))
raise LastfmInvalidResourceError("'%s' by %s: no such track found" % (track, artist))
return result.matches[0]
def searchTrack(self,
track,
artist = None,
@ -193,7 +193,7 @@ class Api(object):
if isinstance(artist, Artist):
artist = artist.name
return Track.search(self, track, artist, limit)
def getUser(self, name):
user = None
try:
@ -202,7 +202,7 @@ class Api(object):
except LastfmError, e:
raise e
return user
def _fetchUrl(self,
url,
@ -225,7 +225,7 @@ class Api(object):
print url
# Get a url opener that can handle basic auth
opener = self._GetOpener(url)
def readUrlData():
now = datetime.now()
delta = now - self._lastFetchTime
@ -261,7 +261,7 @@ class Api(object):
# Always return the latest version
return url_data
def _fetchData(self,
params,
parse = True,
@ -272,17 +272,22 @@ class Api(object):
try:
data = ElementTree.XML(xml)
except SyntaxError, e:
raise LastfmError("Error in parsing XML: %s" % e)
raise LastfmOperationFailedError("Error in parsing XML: %s" % e)
if data.get('status') != "ok":
raise LastfmError("Error code: %s (%s)" % (data.find("error").get('code'), data.findtext('error')))
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)
if parse:
return data
else:
return xml
def __repr__(self):
return "<lastfm.Api: %s>" % self.__apiKey
from datetime import datetime
import sys
import time
@ -292,7 +297,7 @@ import urlparse
from album import Album
from artist import Artist
from error import LastfmError
from error import errorMap, LastfmError, LastfmOperationFailedError, LastfmInvalidResourceError
from event import Event
from filecache import FileCache
from geo import Location, Country
@ -312,4 +317,4 @@ else:
try:
import ElementTree
except ImportError:
raise LastfmError("Install ElementTree package for using python-lastfm")
raise LastfmError("Install ElementTree package for using python-lastfm")

View File

@ -21,7 +21,7 @@ class Artist(LastfmBase):
topTags = None,
bio = None):
if not isinstance(api, Api):
raise LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
self.__mbid = mbid
@ -286,7 +286,7 @@ class Artist(LastfmBase):
mbid = None):
params = {'method': 'artist.getinfo'}
if not (artist or mbid):
raise LastfmError("either artist or mbid has to be given as argument.")
raise LastfmInvalidParametersError("either artist or mbid has to be given as argument.")
if artist:
params.update({'artist': artist})
elif mbid:
@ -353,7 +353,7 @@ class Artist(LastfmBase):
try:
return hash(args[1].lower())
except IndexError:
raise LastfmError("name has to be provided for hashing")
raise LastfmInvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
@ -411,7 +411,7 @@ import time
from album import Album
from api import Api
from error import LastfmError
from error import LastfmInvalidParametersError
from event import Event
from stats import Stats
from tag import Tag

View File

@ -5,4 +5,76 @@ __version__ = "0.1"
__license__ = "GNU Lesser General Public License"
class LastfmError(Exception):
"""Base class for Lastfm errors"""
"""Base class for Lastfm errors"""
def __init__(self,
message = None,
code = None):
self.__code = code
self.__message = message
@property
def code(self):
return self.__code
@property
def message(self):
return self.__message
def __str__(self):
return "%s" % self.message
class LastfmInvalidServiceError(LastfmError):#2
pass
class LastfmInvalidMethodError(LastfmError):#3
pass
class LastfmAuthenticationFailedError(LastfmError):#4
pass
class LastfmInvalidFormatError(LastfmError):#5
pass
class LastfmInvalidParametersError(LastfmError):#6
pass
class LastfmInvalidResourceError(LastfmError):#7
pass
class LastfmOperationFailedError(LastfmError):#8
pass
class LastfmInvalidSessionKeyError(LastfmError):#9
pass
class LastfmInvalidApiKeyError(LastfmError):#10
pass
class LastfmServiceOfflineError(LastfmError):#11
pass
class LastfmSubscribersOnlyError(LastfmError):#12
pass
class LastfmTokenNotAuthorizedError(LastfmError):#14
pass
class LastfmTokenExpiredError(LastfmError):#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
}

View File

@ -23,7 +23,7 @@ class Event(LastfmBase):
stats = None,
tag = None):
if not isinstance(api, Api):
raise LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__id = id
self.__title = title
@ -180,7 +180,7 @@ class Event(LastfmBase):
try:
return hash(kwds['id'])
except KeyError:
raise LastfmError("id has to be provided for hashing")
raise LastfmInvalidParametersError("id has to be provided for hashing")
def __hash__(self):
return Event.hashFunc(id = self.id)
@ -199,6 +199,6 @@ import time
from api import Api
from artist import Artist
from error import LastfmError
from error import LastfmInvalidParametersError
from geo import Venue, Location, Country
from stats import Stats

View File

@ -115,7 +115,7 @@ class Venue(LastfmBase):
try:
return hash(kwds['url'])
except KeyError:
raise LastfmError("url has to be provided for hashing")
raise LastfmInvalidParametersError("url has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(url = self.url)
@ -144,7 +144,7 @@ class Location(LastfmBase):
longitude = None,
timezone = None):
if not isinstance(api, Api):
raise LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
self.__city = city
@ -212,7 +212,7 @@ class Location(LastfmBase):
try:
return hash("name%s" % kwds['name'])
except KeyError:
raise LastfmError("either latitude and longitude or name has to be provided for hashing")
raise LastfmInvalidParametersError("either latitude and longitude or name has to be provided for hashing")
def __hash__(self):
if not self.name:
@ -243,7 +243,7 @@ class Country(LastfmBase):
api,
name = None):
if not isinstance(api, Api):
raise LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
@ -282,7 +282,7 @@ class Country(LastfmBase):
try:
return hash(kwds['name'])
except KeyError:
raise LastfmError("name has to be provided for hashing")
raise LastfmInvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
@ -298,7 +298,7 @@ class Country(LastfmBase):
from api import Api
from artist import Artist
from error import LastfmError
from error import LastfmInvalidParametersError
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 LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
@ -101,7 +101,7 @@ class Group(LastfmBase):
try:
return hash(kwds['name'])
except KeyError:
raise LastfmError("name has to be provided for hashing")
raise LastfmInvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
@ -116,5 +116,5 @@ class Group(LastfmBase):
return "<lastfm.Group: %s>" % self.name
from api import Api
from error import LastfmError
from error import LastfmInvalidParametersError
from weeklychart import WeeklyChart, WeeklyAlbumChart, WeeklyArtistChart, WeeklyTrackChart

View File

@ -32,7 +32,7 @@ class Playlist(LastfmBase):
try:
return hash(kwds['url'])
except KeyError:
raise LastfmError("url has to be provided for hashing")
raise LastfmInvalidParametersError("url has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(url = self.url)
@ -46,4 +46,4 @@ class Playlist(LastfmBase):
def __repr__(self):
return "<lastfm.Playlist: %s>" % self.url
from error import LastfmError
from error import LastfmInvalidParametersError

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 LastfmError
from error import LastfmInvalidParametersError
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 LastfmError("Key does not correspond to a valid class")
raise LastfmInvalidParametersError("Key does not correspond to a valid class")
else:
try:
vals = LastfmBase.registry[eval(name)].values()

View File

@ -16,7 +16,7 @@ class Tag(LastfmBase):
streamable = None,
stats = None):
if not isinstance(api, Api):
raise LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
self.__url = url
@ -222,7 +222,7 @@ class Tag(LastfmBase):
try:
return hash(kwds['name'])
except KeyError:
raise LastfmError("name has to be provided for hashing")
raise LastfmInvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
@ -239,6 +239,6 @@ class Tag(LastfmBase):
from album import Album
from api import Api
from artist import Artist
from error import LastfmError
from error import LastfmInvalidParametersError
from stats import Stats
from track import Track

View File

@ -23,7 +23,7 @@ class Track(LastfmBase):
playedOn = None,
lovedOn = None):
if not isinstance(api, Api):
raise LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
self.__mbid = mbid
@ -104,7 +104,7 @@ class Track(LastfmBase):
track = None,
mbid = None):
if not ((artist and track) or mbid):
raise LastfmError("either (artist and track) or mbid has to be given as argument.")
raise LastfmInvalidParametersError("either (artist and track) or mbid has to be given as argument.")
if artist and track:
params.update({'artist': artist, 'track': track})
@ -262,7 +262,7 @@ class Track(LastfmBase):
try:
return hash("%s%s" % (kwds['name'], hash(kwds['artist'])))
except KeyError:
raise LastfmError("name and artist have to be provided for hashing")
raise LastfmInvalidParametersError("name and artist have to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name, artist = self.artist)
@ -284,7 +284,7 @@ class Track(LastfmBase):
from api import Api
from artist import Artist
from error import LastfmError
from error import LastfmInvalidParametersError
from stats import Stats
from tag import Tag
from user import User

View File

@ -16,7 +16,7 @@ class User(LastfmBase):
image = None,
stats = None):
if not isinstance(api, Api):
raise LastfmError("api reference must be supplied as an argument")
raise LastfmInvalidParametersError("api reference must be supplied as an argument")
self.__api = api
self.__name = name
self.__url = url
@ -460,7 +460,7 @@ class User(LastfmBase):
try:
return hash(kwds['name'])
except KeyError:
raise LastfmError("name has to be provided for hashing")
raise LastfmInvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(name = self.name)
@ -631,7 +631,7 @@ class User(LastfmBase):
try:
return hash(kwds['user'])
except KeyError:
raise LastfmError("user has to be provided for hashing")
raise LastfmInvalidParametersError("user has to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(user = self.user)
@ -645,15 +645,9 @@ import time
from api import Api
from artist import Artist
from album import Album
from error import LastfmError
from error import LastfmError, LastfmInvalidParametersError
from event import Event
from stats import Stats
from tag import Tag
from track import Track
from weeklychart import WeeklyChart, WeeklyAlbumChart, WeeklyArtistChart, WeeklyTrackChart
#TODO
#write exceptions
#argument type checking
#cross check with website
#parse xml in chunks
from weeklychart import WeeklyChart, WeeklyAlbumChart, WeeklyArtistChart, WeeklyTrackChart

View File

@ -43,7 +43,7 @@ class WeeklyChart(LastfmBase):
@staticmethod
def _checkWeeklyChartParams(params, start = None, end = None):
if (start is not None and end is None) or (start is None and end is not None):
raise LastfmError("both start and end have to be provided.")
raise LastfmInvalidParametersError("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,7 +51,7 @@ class WeeklyChart(LastfmBase):
'to': int(calendar.timegm(end.timetuple()))
})
else:
raise LastfmError("start and end must be datetime.datetime instances")
raise LastfmInvalidParametersError("start and end must be datetime.datetime instances")
return params
@ -65,7 +65,7 @@ class WeeklyChart(LastfmBase):
kwds['end']
))
except KeyError:
raise LastfmError("subject, start and end have to be provided for hashing")
raise LastfmInvalidParametersError("subject, start and end have to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(
@ -258,6 +258,6 @@ import calendar
from album import Album
from artist import Artist
from error import LastfmError
from error import LastfmInvalidParametersError
from stats import Stats
from track import Track