Quantcast
Channel: Nuno Mariz - Latest blog entries
Viewing all articles
Browse latest Browse all 31

Twitter user timeline with a Django templatetag

$
0
0
Twitter
A simple templatetag for adding to the template context a variable with the user timeline from Twitter.
It uses the CachedContextUpdatingNodesnippet 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.

Viewing all articles
Browse latest Browse all 31

Trending Articles