Tuesday, March 2, 2010

Simple URL shortener in less than 30 lines of python code

I needed an URL shortener for a project that I'm working on that keeps URLs in their short form for a limited time. No need to go into the details about the project as this URL shortener is a helper hack so we don't need to do last-minute rewrite of the app itself.

As an exercise, I decided to write a fully functional RESTful (*buzz*, *buzz*) app with a persistent store for the URLs. I chose Beaker cache for the storage and bobo as the boilerplate base for the app. Thanks to those two components, the actual script is less than 30 lines of python code.

To save the URL and get it's short ID, you POST the URL to the app. The script is caching the URL for an hour, but it's using persistent storage in case the app crashes (it restores the cache contents). I used my short_id() method I wrote about a while ago to generate the ID for the stored URL. If you supply the ID to the app it will redirect you to the stored URL.

You can check the app the git repo here. Feel free to comment and feel free to use it, of course!

To run the script, use: bobo -f shorty.py (bobo is the command to run an embedded bobo web server).
To save an URL, simply POST to it:
$ curl -d "url=http://www.a13x.info/" http://localhost:8080/
(you'll get something like "ax7dc" returned)
To fetch the URL do: http://localhost:8080/ax7dc. The app will redirect you to the saved URL or throw a 404 if it expired (or it didn't exist).

Simple!