Shortening URL

July 22, 2010

[Warning: This post is a backup recovery from my previous Wordpress blog. All content was automatically converted accessing a MySQL database using a Python script (details). Mostly are in Portuguese but if you are interest I can translate to English. If you found any problem dont’t hesitate to contact me in comments.]

There are many URL shortening services. I just picked one (u.nu) to use from command line interface andchose something really quick and simple. Here's the code:

# -*- coding: utf-8 -*-
from urllib import urlencode
import httplib
import sys

api_url="u.nu"
var = urlencode({'url':sys.argv[1]})
args = "/unu-api-simple?%s" % (var)
conn = httplib.HTTPConnection(api_url)
conn.request("GET",args)
ret = conn.getresponse()
print ret.read()
Download the script here.

Just run passing the URL, for example:

$ python u.py www.coding.com.br

http://u.nu/72mpd

Easy your life by putting the script on your $PATH and execution (+x) file mode. Worth check the API from other services: