Adding your twitter status to a page using python and jQuery
Web Development Tools and Techniques
Twitter is the all the rage these days, if you’re on the web you’d better be broadcasting every thought throught worlds hippest “micro-blogging” format. Even beter is that the twitter API gives us great access to the content that we and other produce on their network. Today we’re going to take a look at how to pull our twitter status in to another page. This is also a great overview of how to pull in information with web services and display it on your site.
Part 1: The Architecture
In order to get around restrictions on Cross Site Scripting we’ll have to setup a proxy for the twitter API that lives on our own domain. Relax, it’s not that hard. This proxy will pull down information from the API and make it available to a bit of javascript that we’ll run on our site to display the status. Got it? Good.
Part 2: The Proxy - use python to get twitter status
The Twitter Api will send back results as XML or JSON. Personally i greatly prefer working with JSON so that’s what i’m using for this example. All the proxy really does is grab the data at the url we specify and make it available for us from within our own domain. Let’s take a look at the code:
#!/usr/bin/python
import urllib2
print "Content-type: text\n\n"
req = urllib2.Request("http://twitter.com/users/show/henryrose.json");
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
You don’t have to know Python to understand what’s going on here. The first two lines simply set the path for Python and then import the urllib2 library.
Then we print content type to tell the browser what we’re sending them.
The interesting stuff comes when we form an http request and assign it to the ‘req’ variable. We then get the response, read it and print the output. You’ll need to run this as a cgi on your server and make sure it’s executable.
Part 3: The Client - use jQuery to display external json
Our client will be a bit of javascript that calls our proxy and prints the output into an element on our page. Let’s jump right in to the code:
var TwitterManager = {
twitterProxyUrl: "path-to-proxy-cgi",
getLastUpdate : function () {
$.getJSON(this.twitterProxyUrl, this.myCallback);
},
myCallback : function (data) {
$("#twitter-status").text(data.status.text);
},
currentStatus : ''
};
TwitterManager.getLastUpdate();
To run this you’ll obviously need to have jQuery included on the page. The getLastUpdate function uses jQuery’s getJSON to grab the data from our proxy, and apply the call back which replaces the content of an element with the id ‘twitter-status’ to the most recent twitter update for the user you defined in the proxy.
And voile! You’ve got your twitter status.
Enjoy.
MT @ November 14, 2008