Created
October 5, 2009 21:05
-
-
Save tkaemming/202470 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from calendar import timegm | |
from datetime import datetime | |
from rfc822 import parsedate | |
from urllib import urlencode | |
from urllib2 import urlopen | |
from django import template | |
from django.utils import simplejson | |
register = template.Library() | |
class TwitterNode(template.Node): | |
def __init__(self, user, variable_name): | |
self.user = user | |
self.variable_name = variable_name | |
def render(self, context): | |
parameters = {'id': self.user} | |
encoded_parameters = urlencode(parameters) | |
url = 'http://twitter.com/statuses/user_timeline.json?%s' % encoded_parameters | |
response = urlopen(url) | |
tweets = simplejson.load(response) | |
for tweet in tweets: | |
timestamp = timegm(parsedate(tweet['created_at'])) | |
tweet['python_date'] = datetime.fromtimestamp(timestamp) | |
context[self.variable_name] = tweets | |
return '' | |
def fetch_tweets(parser, token): | |
""" | |
In templates, call like the following: | |
{% fetch_tweets from your_twitter_username as tweets %} | |
""" | |
bits = token.contents.split() | |
if len(bits) != 5: | |
raise TemplateSyntaxError("fetch_tweets takes exactly four arguments.") | |
if bits[1] != 'from': | |
raise TemplateSyntaxError("The second argument to fetch_tweets must be 'from'.") | |
if bits[3] != 'as': | |
raise TemplateSyntaxError("The fourth argument to fetch_tweets must be 'as'.") | |
user = bits[2] | |
variable_name = bits[4] | |
return TwitterNode(user, variable_name) | |
register.tag(fetch_tweets) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment