arranged imports, refactored events methods (moved the code to Events.fromData method), made the call to register method in base.py threadsafe.

master
Abhinav Sarkar 2008-08-18 13:19:41 +00:00
parent 0fdbc32cf8
commit 291ec6846a
14 changed files with 245 additions and 294 deletions

View File

@ -4,22 +4,21 @@ __author__ = "Abhinav Sarkar"
__version__ = "0.1"
__license__ = "GNU Lesser General Public License"
from album import Album
from api import Api
from artist import Artist
from base import LastfmBase
from error import LastfmError
from api import Api
from registry import Registry
from album import Album
from artist import Artist
from event import Event
from geo import Location, Country
from group import Group
from playlist import Playlist
from registry import Registry
from search import SearchResult
from tag import Tag
from tasteometer import Tasteometer
from track import Track
from user import User
from search import SearchResult
__all__ = ['LastfmError', 'Api', 'Album', 'Artist', 'Event',
'Location', 'Country', 'Group', 'Playlist', 'Tag',

View File

@ -201,7 +201,7 @@ from datetime import datetime
import time
from api import Api
from error import LastfmError
from tag import Tag
from artist import Artist
from error import LastfmError
from stats import Stats
from tag import Tag

View File

@ -177,10 +177,13 @@ class Api(object):
limit = None):
return Tasteometer.compare(self, type1, type2, value1, value2, limit)
def getTrack(self, name, artist = None):
def getTrack(self, track, artist):
if isinstance(artist, Artist):
artist = artist.name
return Track(self, name = name, artist = artist)
result = Track.search(self, track, artist)
if len(result.matches) == 0:
raise LastfmError("'%s' by %s: no such track found" % (track, artist))
return result.matches[0]
def searchTrack(self,
track,
@ -260,22 +263,17 @@ class Api(object):
def __repr__(self):
return "<lastfm.Api: %s>" % self.__apiKey
import sys
import time
import urllib
import urllib2
import urlparse
import time
import sys
if sys.version.startswith('2.5'):
import xml.etree.cElementTree as ElementTree
else:
import cElementTree as ElementTree
from error import LastfmError
from filecache import FileCache
from album import Album
from artist import Artist
from error import LastfmError
from event import Event
from filecache import FileCache
from geo import Location, Country
from group import Group
from playlist import Playlist
@ -283,3 +281,14 @@ from tag import Tag
from tasteometer import Tasteometer
from track import Track
from user import User
if sys.version.startswith('2.5'):
import xml.etree.cElementTree as ElementTree
else:
try:
import cElementTree as ElementTree
except ImportError:
try:
import ElementTree
except ImportError:
raise LastfmError("Install ElementTree package for using python-lastfm")

View File

@ -162,43 +162,7 @@ class Artist(LastfmBase):
data = self.__api._fetchData(params).find('events')
self.__events = [
Event(
self.__api,
id = int(e.findtext('id')),
title = e.findtext('title'),
artists = [Artist(self.__api, name = a.text) for a in e.findall('artists/artist')],
headliner = Artist(self.__api, name = e.findtext('artists/headliner')),
venue = Venue(
name = e.findtext('venue/name'),
location = Location(
self.__api,
city = e.findtext('venue/location/city'),
country = Country(
self.__api,
name = e.findtext('venue/location/country')
),
street = e.findtext('venue/location/street'),
postalCode = e.findtext('venue/location/postalcode'),
latitude = float(e.findtext(
'venue/location/{%s}point/{%s}lat' % ((Location.xmlns,)*2)
)),
longitude = float(e.findtext(
'venue/location/{%s}point/{%s}long' % ((Location.xmlns,)*2)
)),
timezone = e.findtext('venue/location/timezone')
),
url = e.findtext('venue/url')
),
startDate = e.findtext('startDate') and
datetime(*(time.strptime(e.findtext('startDate').strip(), '%a, %d %b %Y')[0:6])) or
None,
startTime = e.findtext('startTime') and
datetime(*(time.strptime(e.findtext('startTime').strip(), '%H:%M')[0:6])) or
None,
description = e.findtext('description'),
image = dict([(i.get('size'), i.text) for i in e.findall('image')]),
url = e.findtext('url')
)
Event.createFromData(self.__api, e)
for e in data.findall('event')
]
return self.__events
@ -447,13 +411,13 @@ class Bio(object):
from datetime import datetime
import time
from api import Api
from album import Album
from api import Api
from error import LastfmError
from event import Event
from geo import Country, Location, Venue
from search import SearchResult
from stats import Stats
from tag import Tag
from track import Track
from user import User
from search import SearchResult
from stats import Stats

View File

@ -4,10 +4,16 @@ __author__ = "Abhinav Sarkar"
__version__ = "0.1"
__license__ = "GNU Lesser General Public License"
try:
from threading import Lock
except ImportError:
from dummy_threading import Lock
class LastfmBase(object):
"""Base class for all the classes in this package"""
registry = {}
_lock = Lock()
def __new__(cls, *args, **kwds):
if 'bypassRegistry' in kwds:
@ -17,9 +23,13 @@ class LastfmBase(object):
return inst
key = cls.hashFunc(*args, **kwds)
LastfmBase._lock.acquire()
try:
inst, alreadyRegistered = LastfmBase.register(object.__new__(cls), key)
if not alreadyRegistered:
inst.init(*args, **kwds)
finally:
LastfmBase._lock.release()
return inst
@staticmethod

View File

@ -31,14 +31,13 @@ class Event(LastfmBase):
self.__headliner = headliner
self.__venue = venue
self.__startDate = startDate
self.__startTime = startTime
self.__description = description
self.__image = image
self.__url = url
self.__stats = stats and Stats(
subject = self,
attendance = self.attendance,
reviews = self.reviews
attendance = stats.attendance,
reviews = stats.reviews
)
self.__tag = tag
@ -72,11 +71,6 @@ class Event(LastfmBase):
"""start date of the event"""
return self.__startDate
@property
def startTime(self):
"""start time of the event"""
return self.__startTime
@property
def description(self):
"""description of the event"""
@ -106,6 +100,41 @@ class Event(LastfmBase):
def getInfo(api, event):
params = {'method': 'event.getinfo', 'event': event}
data = api._fetchData(params).find('event')
return Event.createFromData(api, data)
@staticmethod
def createFromData(api, data):
startDate = None
if data.findtext('startTime') is not None:
startDate = datetime(*(
time.strptime(
"%s %s" % (
data.findtext('startDate').strip(),
data.findtext('startTime').strip()
),
'%a, %d %b %Y %H:%M'
)[0:6])
)
else:
try:
startDate = datetime(*(
time.strptime(
data.findtext('startDate').strip(),
'%a, %d %b %Y %H:%M:%S'
)[0:6])
)
except ValueError:
try:
startDate = datetime(*(
time.strptime(
data.findtext('startDate').strip(),
'%a, %d %b %Y'
)[0:6])
)
except ValueError:
pass
return Event(
api,
@ -134,12 +163,7 @@ class Event(LastfmBase):
),
url = data.findtext('venue/url')
),
startDate = data.findtext('startDate') and
datetime(*(time.strptime(data.findtext('startDate').strip(), '%a, %d %b %Y')[0:6])) or
None,
startTime = data.findtext('startTime') and
datetime(*(time.strptime(data.findtext('startTime').strip(), '%H:%M')[0:6])) or
None,
startDate = startDate,
description = data.findtext('description'),
image = dict([(i.get('size'), i.text) for i in data.findall('image')]),
url = data.findtext('url'),
@ -174,7 +198,7 @@ from datetime import datetime
import time
from api import Api
from error import LastfmError
from artist import Artist
from error import LastfmError
from geo import Venue, Location, Country
from stats import Stats

View File

@ -4,9 +4,9 @@ __author__ = "Abhinav Sarkar"
__version__ = "0.1"
__license__ = "GNU Lesser General Public License"
import tempfile
import os
import md5
import os
import tempfile
class _FileCacheError(Exception):
'''Base exception class for FileCache related errors'''

View File

@ -23,43 +23,7 @@ class Geo(object):
totalResults = int(data.attrib['total']),
itemsPerPage = int(math.ceil(float(data.attrib['total']))/float(data.attrib['totalpages'])),
matches = [
Event(
api,
id = int(e.findtext('id')),
title = e.findtext('title'),
artists = [Artist(api, name = a.text) for a in e.findall('artists/artist')],
headliner = Artist(api, name = e.findtext('artists/headliner')),
venue = Venue(
name = e.findtext('venue/name'),
location = Location(
api,
city = e.findtext('venue/location/city'),
country = Country(
api,
name = e.findtext('venue/location/country')
),
street = e.findtext('venue/location/street'),
postalCode = e.findtext('venue/location/postalcode'),
latitude = float(e.findtext(
'venue/location/{%s}point/{%s}lat' % ((Location.xmlns,)*2)
)),
longitude = float(e.findtext(
'venue/location/{%s}point/{%s}long' % ((Location.xmlns,)*2)
)),
timezone = e.findtext('venue/location/timezone')
),
url = e.findtext('venue/url')
),
startDate = e.findtext('startDate') and
datetime(*(time.strptime(e.findtext('startDate').strip(), '%a, %d %b %Y')[0:6])) or
None,
startTime = e.findtext('startTime') and
datetime(*(time.strptime(e.findtext('startTime').strip(), '%H:%M')[0:6])) or
None,
description = e.findtext('description'),
image = dict([(i.get('size'), i.text) for i in e.findall('image')]),
url = e.findtext('url')
)
Event.createFromData(self.__api, e)
for e in data.findall('event')
]
)
@ -319,14 +283,14 @@ class Country(LastfmBase):
def __repr__(self):
return "<lastfm.geo.Country: %s>" % self.name
import math
from datetime import datetime
import math
import time
from api import Api
from error import LastfmError
from artist import Artist
from track import Track
from error import LastfmError
from event import Event
from search import SearchResult
from stats import Stats
from track import Track

View File

@ -4,11 +4,10 @@ __author__ = "Abhinav Sarkar"
__version__ = "0.1"
__license__ = "GNU Lesser General Public License"
from base import LastfmBase
from error import LastfmError
from album import Album
from artist import Artist
from base import LastfmBase
from error import LastfmError
from event import Event
from geo import Location, Country
from group import Group
@ -16,12 +15,11 @@ from playlist import Playlist
from tag import Tag
from track import Track
from user import User
from search import SearchResult
class Registry(object):
"""The registry to contain all the entities"""
keys = [Album, Artist, Event, Location, Country, Group,
Playlist, Tag, Track, User, SearchResult]
Playlist, Tag, Track, User]
def get(self, name):
if name not in Registry.keys:

View File

@ -4,12 +4,10 @@ __author__ = "Abhinav Sarkar"
__version__ = "0.1"
__license__ = "GNU Lesser General Public License"
from base import LastfmBase
class SearchResult(LastfmBase):
class SearchResult(object):
"""A class to represent a search result"""
xmlns = "http://a9.com/-/spec/opensearch/1.1/"
def init(self,
def __init__(self,
type = None,
searchTerms = None,
startPage = None,
@ -64,33 +62,6 @@ class SearchResult(LastfmBase):
def topMatch(self):
return (len(self.matches) and self.matches[0] or None)
@staticmethod
def hashFunc(*args, **kwds):
try:
return hash("%s%s%s" % (kwds['searchTerms'], kwds['type'], kwds['startPage']))
except KeyError:
raise LastfmError("searchTerms, type and startPage have to be provided for hashing")
def __hash__(self):
return self.__class__.hashFunc(
searchTerms = self.searchTerms,
type = self.type,
startPage = self.startPage
)
def __eq__(self, other):
return (
self.searchTerms == other.searchTerms and
self.type == other.type and
self.startIndex == other.startIndex
)
def __lt__(self, other):
if self.searchTerms != other.searchTerms:
return self.searchTerms < other.searchTerms
else:
return self.startIndex < other.startIndex
def __repr__(self):
return "<lastfm.SearchResult: for %s '%s'>" % (self.type, self.searchTerms)

View File

@ -230,10 +230,10 @@ class Tag(LastfmBase):
def __repr__(self):
return "<lastfm.Tag: %s>" % self.name
from api import Api
from error import LastfmError
from album import Album
from api import Api
from artist import Artist
from track import Track
from stats import Stats
from error import LastfmError
from search import SearchResult
from stats import Stats
from track import Track

View File

@ -12,7 +12,7 @@ class Tasteometer(object):
artists = None):
self.__score = score
self.__matches = matches
self.__artists = artists#set
self.__artists = artists
@property
def score(self):
@ -64,5 +64,3 @@ class Tasteometer(object):
return "<lastfm.Tasteometer>"
from artist import Artist
from error import LastfmError

View File

@ -259,9 +259,9 @@ class Track(LastfmBase):
return "<lastfm.Track: '%s' by %s>" % (self.name, self.artist.name)
from api import Api
from error import LastfmError
from user import User
from tag import Tag
from stats import Stats
from artist import Artist
from error import LastfmError
from search import SearchResult
from stats import Stats
from tag import Tag
from user import User

View File

@ -25,6 +25,7 @@ class User(LastfmBase):
match = stats.match,
weight = stats.weight
)
self.__events = None
@property
def name(self):
@ -48,6 +49,18 @@ class User(LastfmBase):
@property
def events(self):
if self.__events is None:
params = {'method': 'user.getevents', 'user': self.name}
data = self.__api._fetchData(params).find('events')
self.__events = [
Event.createFromData(self.__api, e)
for e in data.findall('event')
]
return self.__events
@property
def pastEvents(self):
pass
def getFriends(self,
@ -190,4 +203,5 @@ class User(LastfmBase):
from api import Api
from error import LastfmError
from event import Event
from stats import Stats