How to make unique short URL with Python? How to make unique short URL with Python? python python

How to make unique short URL with Python?


Edit: Here, I wrote a module for you. Use it. http://code.activestate.com/recipes/576918/


Counting up from 1 will guarantee short, unique URLS. /1, /2, /3 ... etc.

Adding uppercase and lowercase letters to your alphabet will give URLs like those in your question. And you're just counting in base-62 instead of base-10.

Now the only problem is that the URLs come consecutively. To fix that, read my answer to this question here:

Map incrementing integer range to six-digit base 26 max, but unpredictably

Basically the approach is to simply swap bits around in the incrementing value to give the appearance of randomness while maintaining determinism and guaranteeing that you don't have any collisions.


I'm not sure most URL shorteners use a random string. My impression is they write the URL to a database, then use the integer ID of the new record as the short URL, encoded base 36 or 62 (letters+digits).

Python code to convert an int to a string in arbitrary bases is here.


Python's short_url is awesome.

Here is an example:

import short_urlid = 20  # your object iddomain = 'mytiny.domain' shortened_url = "http://{}/{}".format(                                     domain,                                     short_url.encode_url(id)                               )

And to decode the code:

decoded_id = short_url.decode_url(param)

That's it :)

Hope this will help.