Blog entries on February 2008

  • I'm addicted

    By Nuno Mariz, on 28 February 2008 @ 14:46
    Nike Plus
  • Twitter user timeline with a Django templatetag

    By Nuno Mariz, on 11 February 2008 @ 10:45
    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
    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):
                response = urllib.urlopen('' % self.username).read()
                json = simplejson.loads(response)
                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}
    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])
    {% 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.