May 20

Twitter updates in blog

Date: May 20, 2009. Comments»

You are a twitter hero and like to show twits on your blog or twitter update this post is for you. So how to do it? Its pretty simple if you don't have a private updates. Just make a request to http://twitter.com/statuses/user_timeline/.format. Format can be either xml or json.

>>> from xml.dom import minidom
>>> import urllib2
>>> req = urllib2.Request('http://twitter.com/statuses/user_timeline/google.xml')
>>> response = urllib2.urlopen(req)
>>> xml = response.read()
>>> dom_object = minidom.parseString(xml)
>>> tags = dom_object.getElementsByTagName('text')
>>> for text in tags:
    ... print text.toxml()
... Power to the people! Announcing our first Google PowerMeter partners http://bit.ly/POraB
RT @googlereader Find out about the latest set of Reader tweaks http://bit.ly/155AOM
Making Spock proud: Gmail Labs auto-translates email in 41 languages http://bit.ly/oC1Q6
Congratulations to the class of 2009! Commencement addresses from Googlers http://bit.ly/17PBCb
RT @GoogleAtWork: Don't take a rain check, check for rain - 4 day weather forecast right in Google Calendar: http://bit.ly/7KXjc
Easy go, easy come: Gmail makes it braindead-simple to import mail from your other accounts http://bit.ly/14SSed
Attention video game vets. Remember Galaxy Game? One of our guys does http://bit.ly/g8UyD
RT @kevinmarks - Google I/O Ignite speakers announced: http://bit.ly/P6tbJ #ignite #googleio
RT @googlestudents: Marissa Mayer delivers the commencement address at the Illinois Institute of Technology on May 16 http://bit.ly/14bO3z

If you have private update, set your username and password in HTTP header and get the update or you can use Python twitter. If you are using google app engine for your application, app engine doesn't allow your to have a file cache or extensively use tempfile which is the case with Python twitter. Now all you have to do is roll up your sleeves and disable to file cache and use app engines memcache. I will tell you how to do it.

Download python twitter and open twitter.py, go to the _FetchUrl function you can see a comment "# Open and return the URL immediately" add these line above that comment
url_data = opener.open(url).read() return url_data
and change the line import simplejson to from django.utils import simplejson. Now all set If you want to hit twitter api for each and every hit on your page it will be ridiculous and time taking. So, the solution is memcache.
data = memcache.get("twitter")
if data is not None:
  return data
else:
  api = twitter.Api(username='foobar', password='buz')
  data = api.GetUserTimeline('foobar')[0:5]
  memcache.add("twitter", data, 3600)
  return data
3600 is seconds after which the cache will expire. Mail me if you have some issue with disabling the file cache in python twitter.

Comments

Leave Comment: