Last.fm Charts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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)

More like this

  1. Custom SQL Function; Outputs Template-Friendly Content by hotani 6 years, 11 months ago
  2. generateChart() for creating a Google Chart API pie chart from JavaScript by simon 5 years, 1 month ago
  3. Google Charts Templatetags (Python) by justquick 5 years, 9 months ago
  4. Filter to generate QR codes by javinievas 3 years, 8 months ago
  5. Google Charts Templatetags (HTML) by justquick 5 years, 11 months ago

Comments

(Forgotten your password?)