sankaet sankaet - 3 months ago 7
Javascript Question

URL detection and shortening in Django

I was just wondering if there is a way in Django to detect URLs from a bunch of text and then shorten them up automatically. I know I can use urlize to detect urls, but I am not sure if I can use maybe bitly or something to shorten the links.

And also would it be better to accomplish this task with javascript instead of python? and if that is the case how do I go about it?

Answer

For bit.ly if you just want to shorten URLs, its quite simple:

First create an account, and then visit http://bitly.com/a/your_api_key to get your API key.

Send a request to the shorten method of the API, the result is your shortened URL:

from urllib import urlencode
from urllib2 import urlopen

ACCESS_KEY = 'blahblah'
long_url = 'http://www.example.com/foo/bar/zoo/hello/'
endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt'
req = urlencode(endpoint.format(ACCESS_KEY, long_url))
short_url = urlopen(req).read()

You can wrap that up into a template tag:

@register.simple_tag
def bitlyfy(the_url):
    endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt'
    req = urlencode(endpoint.format(settings.ACCESS_KEY, the_url))
    return urlopen(req).read()

Then in your template:

{% bitlyfy "http://www.google.com" %}

Note: Positional arguments in tags are a feature of django 1.4

If you want the all the features of the bit.ly API, start by reading the documentation at dev.bitly.com/get_started.html, and then download the official python client.

Comments