Commits

Stefan Scherfke  committed bf7228a

Flake8-ified the code.

  • Participants
  • Parent commits bc75b12

Comments (0)

Files changed (4)

File lastfm/templatetags/lastfm_widget.py

 # encoding: utf-8
-
 """
-This module defines a single template tag that will return a context object
-for your Last.fm widget. It contains a title for the widget and a ``<div>`` container. This container includes the AJAX code that retrieves the data
-from the ``lastfm`` view and generates an image for each item.
+This module defines a single template tag that will return a context object for
+your Last.fm widget. It contains a title for the widget and a ``<div>``
+container. This container includes the AJAX code that retrieves the data from
+the ``lastfm`` view and generates an image for each item.
 
 .. sourcecode:: html+django
 
     {% load lastfm_widget %}
-    
+
     {% get_lastfm_widget as lastfm_widget %}
     <h2>{{ lastfm_widget.title }}</h2>
     {{ lastfm_widget.content }}
-    
+
 The generated code will roughly look like this:
 
 .. sourcecode:: html
 
 class LastfmWidgetNode(template.Node):
     """
-    This class will create a context object named ``var_name``. It will contain 
+    This class will create a context object named ``var_name``. It will contain
     the ``title`` and the ``content`` of the widget.
-    
+
     """
     def __init__(self, var_name):
         self.var_name = var_name
-        
+
     def render(self, context):
         """Load the template and render it into a context variable."""
         t = template.loader.get_template('lastfm_widget/_widget.html')
             'content': t.render(template.Context({},
                     autoescape=context.autoescape)),
         }
-        
+
         context[self.var_name] = lastfm_widget
         return ''
 
     try:
         tagname, _as, var_name = token.split_contents()
     except ValueError:
-        raise template.TemplateSyntaxError('%r tag requires two arguments.' % 
+        raise template.TemplateSyntaxError('%r tag requires two arguments.' %
                 token.contents.split()[0])
     return LastfmWidgetNode(var_name)

File lastfm/tests.py

 
 class TemplateTagsTestCase(TestCase):
     """Test the template tag for the last.fm widget."""
-    
+
     def setUp(self):
         self.parser = mock.Mock(spec=['compile_filter'])
         self.token = mock.Mock(spec=['split_contents'])
-        
+
     def test_get_sidebar_widgets(self):
         """
         Test if ``lastfm_widget.get_lastfm_widget()`` returns a node with the
         correct variable name.
-        
+
         """
         tag = 'get_lastfm_widget'
         var_name = 'widgets'
         self.token.split_contents.return_value = (tag, 'as', var_name)
-        
+
         node = lastfm_widget.get_lastfm_widget(self.parser, self.token)
         self.assertEqual(node.var_name, var_name)
-        
+
     @mock.patch('django.template.loader.get_template')
     @mock.patch('django.template.Context')
     def test_lastfm_widget_node(self, get_template, Context):
         """
         Test if the template node contains the correct template variables.
-        
+
         """
         class ContextMock(dict):
             autoescape = object()
         context = ContextMock()
-        template = get_template.return_value
-    
+        # template = get_template.return_value
+
         var_name = 'widgets'
         node = lastfm_widget.LastfmWidgetNode(var_name)
-        node.render(context)     
-        
+        node.render(context)
+
         self.assertTrue(var_name in context)
         widget = context[var_name]
         self.assertTrue('title' in widget)

File lastfm/views.py

 
 """
 The AJAX code generate by the template tag (see
-:mod:`lastfm.templatetags.lastfm_widget`) doesn’t contact Last.fm directly, but
-uses a Django view as proxy. The advantage of this is, that you can exactly
-control what data your site gets. Another advantage is, that visitors can’t see
-your Last.fm username by inspecting the HTML source of your site.
+:mod:`lastfm.templatetags.lastfm_widget`) doesn’t contact Last.fm directly,
+but uses a Django view as proxy. The advantage of this is, that you can
+exactly control what data your site gets. Another advantage is, that visitors
+can’t see your Last.fm username by inspecting the HTML source of your site.
 
-In addition to the view itself this module also defines some helper classes that
-are responsible for handling the different types of charts (e.g. top tracks or
-top artists).
+In addition to the view itself this module also defines some helper classes
+that are responsible for handling the different types of charts (e.g. top
+tracks or top artists).
 
 """
 
 LASTFM_WIDGET_TITLE = getattr(settings, 'LASTFM_WIDGET_TITLE',
         'Weekly Top Artists')
 LASTFM_NUM_IMAGES = getattr(settings, 'LASTFM_NUM_IMAGES', '12')
-LASTFM_TOP_ARTISTS_PERIOD = getattr(settings, 'LASTFM_TOP_ARTISTS_PERIOD', 
+LASTFM_TOP_ARTISTS_PERIOD = getattr(settings, 'LASTFM_TOP_ARTISTS_PERIOD',
         '7day')
 LASTFM_IMG_SIZE = getattr(settings, 'LASTFM_IMG_SIZE', 'large')
 
 def lastfm_data(request):
     """
     This view retrievs the data from Last.fm and returns a JSON encoded list.
-    The template tag’s AJAX code will retrive this list and generate the chart
-    from it.
-    
+    The template tag’s AJAX code will retrieve this list and generate the
+    chart from it.
+
     Each list entry is a dict with three elements:
-     * ``title``: Contains the song title or artist name and can be displayed as
-       alternative text or link title.
+     * ``title``: Contains the song title or artist name and can be displayed
+       as alternative text or link title.
      * ``url``: A url pointing to the track or artist on Last.fm.
      * ``img_url``: A url pointing to the track’s cover or artist image.
-    
+
     For each chart type there is a class that handles its data. They are
     necessary to unify Last.fm’s different key names to those three explained
     above. Currently, there is no abstract base class which they must inherit
     from, but each class is expected to implement the following attributes and
     methods:
-    
-    ``params``: A dict that contains all parameters required by the `Last.fm API
-    call <http://www.lastfm.de/api>`_
-    
-    ``get_data(data)``: Last.fm’s JSON data is quite nested. This method should
-    extract the list with the actual items from the raw data.
-    
-    ``get_item_title(item)``: Return an item’s text for the ``title`` attribute
-    in the data dict.
-    
+
+    ``params``: A dict that contains all parameters required by the `Last.fm
+    API call <http://www.lastfm.de/api>`_
+
+    ``get_data(data)``: Last.fm’s JSON data is quite nested. This method
+    should extract the list with the actual items from the raw data.
+
+    ``get_item_title(item)``: Return an item’s text for the ``title``
+    attribute in the data dict.
+
     ``get_default_image()``: Return a url to a default image that will be used
     if a track or artist has no image on its own.
-    
-    ``get_img_url(img_size, item)``: This method needs to be implemented only if
-    an item has no ``image`` key (which is the case for e.g. the weekly top
+
+    ``get_img_url(img_size, item)``: This method needs to be implemented only
+    if an item has no ``image`` key (which is the case for e.g. the weekly top
     artist). It gets the desired image size (small, medium, large, …) and the
     item. It might do another API call and extract a custom image URL for that
     item.
-    
+
     """
     chart_types = {
         'recent_tracks': RecentTracks,
         'top_artists': TopArtists,
     }
     img_size = LASTFM_IMG_SIZE
-        
+
     chart = chart_types[LASTFM_CHART_TYPE]()
-    
+
     try:
         params = urllib.urlencode(chart.params)
         data = json.loads(urllib.urlopen(URL + params).read())
-        
+
         if 'error' in data:
             raise RuntimeError(str(data))
-        
+
         data = chart.get_data(data)
         if not data:
             raise IOError('No artists found.')
             data = [data]
     except IOError:
         return HttpResponse(json.dumps([]), mimetype='application/json')
-    
+
     items = []
     for i, d in enumerate(data):
         # Not every last.fm method supports the ``limit`` parameter so we have
         # to take care of this ourselves.
         if i == int(LASTFM_NUM_IMAGES):
             break
-        
+
         item = {
             'title': chart.get_item_title(d),
             'url': d['url'],
             'img_url': chart.get_default_image(),
         }
-        
+
         if 'image' in d:
             for img in d['image']:
                 if img['size'] == img_size and img['#text']:
                     break
         else:
             item['img_url'] = chart.get_img_url(img_size, d)
-        
+
         items.append(item)
-        
+
     return HttpResponse(json.dumps(items), mimetype='application/json')
-        
+
+
 class RecentTracks(object):
     """This class handles the API call ``user.getRecentTracks``."""
     params = {
         'api_key': LASTFM_API_KEY,
         'format': 'json',
     }
-    
+
     def get_data(self, data):
         return data['recenttracks']['track']
-        
+
     def get_item_title(self, item):
         return u'%s – %s' % (item['artist']['#text'], item['name'])
-        
+
     def get_default_image(self):
         return 'http://cdn.last.fm/depth/catalogue/noimage/cover_85px.gif'
 
-        
+
 class WeeklyTopArtists(object):
     """This class handles the API call ``user.getWeeklyArtistChart``."""
     params = {
         'api_key': LASTFM_API_KEY,
         'format': 'json',
     }
-    
+
     def get_data(self, data):
         return data['weeklyartistchart']['artist']
-        
+
     def get_item_title(self, item):
         return '%s (%s plays)' % (item['name'], item['playcount'])
-        
+
     def get_default_image(self):
         return 'http://cdn.last.fm/flatness/catalogue/noimage/2/' + \
                 'default_artist_large.png'
 
     def get_img_url(self, img_size, item):
         """
-        A chart item of this class does not contain any images, so we need to do
-        another API call to get an image for artist in ``item``.
-        
+        A chart item of this class does not contain any images, so we need to
+        do another API call to get an image for artist in ``item``.
+
         """
         params = urllib.urlencode({
             'method': 'artist.getimages',
             'api_key': LASTFM_API_KEY,
             'format': 'json',
         })
-        
+
         try:
-            img_data = json.loads(urllib.urlopen(URL + params).read())['images']
+            img_data = json.loads(urllib.urlopen(
+                    URL + params).read())['images']
         except IOError:
             return ''
         if 'image' in img_data:
             for img in img_data:
                 if img['name'] == img_size and img['#text']:
                     return img['#text']
-    
-    
+
+
 class TopArtists(object):
     """
-    This class handles the API call ``user.getTopArtists``. The period must be 
+    This class handles the API call ``user.getTopArtists``. The period must be
     defined in the site’s settings module.
-    
+
     """
     params = {
         'method': 'user.getTopArtists',
         'user': LASTFM_USER,
         'api_key': LASTFM_API_KEY,
         'period': LASTFM_TOP_ARTISTS_PERIOD,
-        'format': 'json'
+        'format': 'json',
     }
-    
+
     def get_data(self, data):
         return data['topartists']['artist']
-        
+
     def get_item_title(self, item):
         return '%s (%s plays)' % (item['name'], item['playcount'])
-        
+
     def get_default_image(self):
         return 'http://cdn.last.fm/flatness/catalogue/noimage/2/' + \
                 'default_artist_large.png'
 #! /usr/bin/env python
 # encoding: utf-8
-
 from distutils.core import setup
 
 
     download_url='http://bitbucket.org/scherfke/django-lastfm/downloads/',
     license='BSD',
     packages=[
-        'lastfm', 
+        'lastfm',
         'lastfm.templatetags',
     ],
     package_data={