Login

Latest tweets Templatetag

Author:
javinievas
Posted:
January 23, 2011
Language:
Python
Version:
1.2
Tags:
templatetag twitter social
Score:
1 (after 3 ratings)

Based on http://djangosnippets.org/snippets/1615/

Added tweets cache. Cache time is configurable through project settings: TWITTER_TIMEOUT=300. Default time is 300 seconds = 5 minutes. This improve performance by reducing the twitter api queries interval.

 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
46
47
48
49
50
51
52
import twitter
from django.core.cache import cache
from django.conf import settings

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):
        cache_key = "latest_tweets_%s_%d" % (self.user, self.limit)
        cached_elems = cache.get(cache_key, None)
        if cached_elems:
            context[self.tweets] = cached_elems
        else:
            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
		cache.set(cache_key, most_recent_messages, settings.get.("TWITTER_TIMEOUT", 300))
            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

  1. Template tag: Last x twitter msgs of user by coulix 6 years ago
  2. Twitter template tags and filters by moxypark 4 years, 11 months ago
  3. automating twitter by lawgon 6 years ago
  4. Image inlining template tag lib by rbeck 4 years, 8 months ago
  5. tweetparser filter by VincentLoy 1 month ago

Comments

Please login first before commenting.