A template tag which returns the n last tweets of a given user.
It uses the twitter python lib.
{% get_twitter_messages user foo limit 5 as tweets %} {% for tweet in tweets %} {{ tweet.text }} {{ tweet.time }} {{ tweet.url }} {% endfor %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import twitter
register = Library()
class TwitterLattestMsgNode(Node):
def __init__(self, user, limit, tweets):
self.tweets = tweets
self.user = user
self.limit = int(limit)
def render(self, context):
try:
api = twitter.Api()
status_obj = api.GetUserTimeline(self.user)
most_recent_messages = [{"text":s.text,
"time":s.relative_created_at,
"url": "http://twitter.com/%s/statuses/%s" % (self.user, s.id),} \
for s in status_obj][:self.limit]
context[self.tweets] = most_recent_messages
except:
context[self.tweets] = {
"error": "Ack! Looks like Twitter's codes are broken!",
}
return ''
@register.tag(name='get_twitter_messages')
def twitter_status(parser, token):
"""
Call this tag with:
get_twitter_status as tweet
"""
bits = token.split_contents()
if len(bits) != 7:
raise TemplateSyntaxError, "%s takes 7 arguments" % bits[0]
if bits[1] != "user":
raise TemplateSyntaxError, "First argument for %s should be 'user'" % bits[0]
if bits[3] != "limit":
raise TemplateSyntaxError, "Second argument for %s should be 'limit'" % bits[0]
if bits[5] != "as":
raise TemplateSyntaxError, "Third argument for %s should be 'as'" % bits[0]
return TwitterLattestMsgNode(bits[2], bits[4], bits[6])
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.