Login

Parsed RSS into template var

Author:
bram
Posted:
July 4, 2008
Language:
Python
Version:
.96
Score:
-1 (after 3 ratings)

loads a parsed RSS feed (with feedparser) into a variable of choice. Caching by the "cache" template tag.

 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
from django import template
import feedparser

register = template.Library()

class RssParserNode(template.Node):
    def __init__(self, var_name, url=None, url_var_name=None):
        self.url = url
        self.url_var_name = url_var_name
        self.var_name = var_name

    def render(self, context):
        if self.url:
            context[self.var_name] = feedparser.parse(self.url)
        else:
            try:
                context[self.var_name] = feedparser.parse(context[self.url_var_name])
            except KeyError:
                raise template.TemplateSyntaxError, "the variable \"%s\" can't be found in the context" % self.url_var_name
        return ''

import re

@register.tag(name="get_rss")
def get_rss(parser, token):
    # This version uses a regular expression to parse tag contents.
    try:
        # Splitting by None == splitting by spaces.
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
    
    m = re.search(r'(.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
    url, var_name = m.groups()
    
    if url[0] == url[-1] and url[0] in ('"', "'"):
        return RssParserNode(var_name, url=url[1:-1])
    else:
        return RssParserNode(var_name, url_var_name=url)
    
"""
example usage:

{% load cache %}
{% load rss %}

{% cache 500 rss_display %}
	{% get_rss "http://www.freesound.org/blog/?feed=rss2" as rss %}
	{% for entry in rss.entries %}
		<h1>{{entry.title}}</h1>
		<p>
			{{entry.summary|safe}}
		</p>
		<p>
			<a href="{{entry.link}}">read more...</a>
		</p>
	{% endfor %}
{% endcache %}
"""

More like this

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

Comments

ericflo (on July 4, 2008):

django-feedutil and django-template-utils both have almost this exact same feature already. But I have to admit, it's kind of nice as a self-contained snippet.

#

bram (on July 31, 2008):

I've edited it slightly, now it can also take a template-variable. For example:

{% get_rss rss_url as rss %}

#

Please login first before commenting.