Login

Last.fm Charts

Author:
sedden
Posted:
July 5, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

This will fetch the Top Artists List for the given username from Last.fm. It makes use of the django.cache Framework. I use it with django 0.96.2. Enjoy!

Usage:

{% load lastfm %} {% lastfm_topartists YourName as topartists %} {% for artist in topartists %} {{ artist.thumbnail }}, {{ artist.name }}, {{ artist.url }}, {{ artist.playcount }} and so on {% endfor %}

 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. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.