ichiba.ch Download the KAYWA Reader!
En | De | Fr

Feed2Mobile

Nuno Mariz Weblog - Latest Posts - Twitter user timeline with a Django templatetag


A simple templatetag for adding to the template context a variable with the user timeline from Twitter.
It uses the CachedContextUpdatingNode snippet for caching from Jacob Kaplan-Moss.
The reason that is necessary to cache content is because Twitter limits the number of accesses to the API.
This only works if the cache is enabled on your settings.py.
class TwitterNode(CachedContextUpdatingNode):

    cache_timeout = 1800 # 30 Minutes, maybe you want to change this
    
    def __init__(self, username, varname):
        self.username = username
        self.varname = varname

    def make_datetime(self, created_at):
        return datetime.fromtimestamp(mktime(strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')))

    def get_cache_key(self, context):
        return 'twitter_user_timeline_cache'

    def get_content(self, context):
        try:
            response = urllib.urlopen('http://twitter.com/statuses/user_timeline/%s.json' % self.username).read()
            json = simplejson.loads(response)
        except:
            return {self.varname : None}
        for i in range(len(json)):
            json[i]['created_at'] = self.make_datetime(json[i]['created_at'])
        return {self.varname : json}
    
@register.tag
def twitter_user_timeline(parser, token):
    bits = token.contents.split()
    if len(bits) != 4:
        raise TemplateSyntaxError, "twitter_user_timeline tag takes exactly three arguments"
    if bits[2] != 'as':
        raise TemplateSyntaxError, "second argument to twitter_user_timeline tag must be 'as'"
    return TwitterNode(bits[1], bits[3])
Usage:
{% twitter_user_timeline username as twitter_entries %}
{% if twitter_entries %}
  {% for entry in twitter_entries %}
  {{ entry.created_at|date:"d M Y H:i" }} - {{ entry.text }}
  {% endfor %}
{% endif %}
Use the source, Luke.

Note: this is how this feed will look on your mobile device.

Get mobile!

This QR Code will let any user whose mobile phone is equipped with a QR Code Reader to easily reach and bookmark the mobile version of «Nuno Mariz Weblog - Latest Posts»

To add this QR Code to your Blog or Website, simply copy-paste the following Javascript blurb into your Blog template.

Feed2Mobile v1.0-BETA3 CONTACT US: KAYWA // TECHNOPARKSTRASSE 1 // 8005 ZUERICH // SWITZERLAND // info@kaywa.com