How to make unique short URL with Python?

Esteban Feldman picture Esteban Feldman · Sep 30, 2009 · Viewed 31.6k times · Source

How can I make unique URL in Python a la http://imgur.com/gM19g or http://tumblr.com/xzh3bi25y When using uuid from python I get a very large one. I want something shorter for URLs.

Answer

FogleBird picture FogleBird · Sep 30, 2009

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.