Today, I reveal the secrets behind the flickr photo box to your left. Alternately: how easy and fun web programming can be with good tools. Also alternately: a shameless plug for software I like, including my own.

Flickr

First things first, we need a way to get some information from Flickr about the photos you want to display. You can pick from an assortment of Flickr API libraries out there, but since this is my blog, I'll use mine. The code really boils down to something like this:

flickr = FlickrAPI( API_KEY )
user = flickr.urls.getUserPhotos( user_id=USER_ID )
photos = flickr.photos.search( user_id=USER_ID )

Now you have a list of photos with enough information to build thumbnail images and links. FlickrAPI even gives you a get_photo_url function that will build the image url for you. user.url also contains the link for your user's photos on flickr.com. Picking random images using the API could definitely be made easier (Flickr: please give us a sort="random").

Django (and simplejson)

Next, we need a way to get this information to the browser. Using Django and simplejson, this is four lines of code. Here's my django view:

def flickr( req ):
    num = int( req.GET.get('num',4) )
    photos = get_random_photos( num )
    return HttpResponse( simplejson.dumps(photos) )

Really, anything that will return a JSON string containing an array of objects, each with thumb, link, and title keys will do.

MochiKit

The last piece of the puzzle, and arguably the most complex, is how to transform this string into a box of pictures, and do so asynchronously. It turns out, MochiKit makes this ridiculously easy, especially if you have any experience with Twisted. In two lines, MochiKit will fire off the HTTP request in the background, and set up a callback function to be executed when it gets a result:

var d = loadJSONDoc( '/flickr/?num=6' );
d.addCallback( gotPhotos );

The beauty of JSON is that you get back actual javascript objects when you eval the string. MochiKit further simplifies this, so your gotPhotos function will be called with an already-eval'd object. Bonus: The DOM manipulation functions are ultra-convenient, so creating a div with the images in it is super easy.

I hope this has been somewhat helpful. Feel free to use any of this code in your projects. Now go forth and scrub!