from django import template from django.core.cache import cache from xml.sax import parseString from xml.sax.handler import ContentHandler from urllib2 import urlopen register = template.Library() class XmlTopArtists(ContentHandler): def __init__ (self): self.current_artist = None self.current_tag = None self.current_data = '' self.list = [] def startElement(self, name, attrs): if name == 'artist': self.current_artist = {} else: self.current_tag = name self.current_data = '' def characters (self, char): self.current_data += char def endElement(self, name): if name == 'artist': self.list.append(self.current_artist) else: self.current_artist[self.current_tag] = self.current_data.strip() class TopArtistsNode(template.Node): def __init__(self, user, var_name): self.user = user self.var_name = var_name self.artists = XmlTopArtists() try: data = cache.get(var_name) if data == None: url = 'http://ws.audioscrobbler.com/1.0/user/%s/topartists.xml?type=overall' % (user) data = urlopen(url).read() cache.set(var_name, data, 3600) parseString(data, self.artists) except Exception: pass def render(self, context): context[self.var_name] = self.artists.list return '' @register.tag(name="lastfm_topartists") def do_list_topartists(parser, token): try: tag_name, user, trash, var_name = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents[0] return TopArtistsNode(user, var_name)