Twitter user timeline with a Django templatetag

By Nuno Mariz, on 11 February 2008 @ 10:45
Twitter
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.

Comments

  • #1 By Pedro on 20 October 2010 @ 16:21
    Me again. After adding all the imports it worked great. These lines have to be first to make it work:
    ---
    from template_cache import CachedContextUpdatingNode
    from django.template import Library, Node
    from django.utils import simplejson
    from datetime import datetime
    from time import mktime, strptime
    import urllib
    ---
    [NOTE: `template_cache` is the snippet mentioned above made by some guy called Jacob :P]

    I also added an extra argument: an integer before the username to be able to set how many twits we want to get.
    Example:
    {% twitter_user_timeline 3 pedromagnus as twitter_entries %}
    this would get the last 3 twits from pedromagnus twitter.

    Cheers!
    Pedro
  • #2 By chris on 4 January 2011 @ 01:32
    The caching doesn't seem to be doing for some reason. Copied source and am using the template tag, but my database isn't being filled and there is no error.
Comments are closed.