Generate unique ID for URL
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Nov 13 21:04:26 EST 2012
On Tue, 13 Nov 2012 16:13:58 -0800, Miki Tebeka wrote:
>> I want to create a URL-safe unique ID for URL's. What do you recommend?
>> - Compression?
> You can use base62 with a running counter, but then you'll need a (semi)
> centralized entity to come up with the next id.
>
> You can see one implementation at http://bit.ly/PSJkHS (AppEngine
> environment).
Perhaps this is a silly question, but if you're using a running counter,
why bother with base64? Decimal or hex digits are URL safe. If there are
no concerns about predictability, why not just use the counter directly?
You can encode a billion IDs in 8 hex digits compared to 16 base64
characters:
py> base64.urlsafe_b64encode('1000000000')
'MTAwMDAwMDAwMA=='
py> "%x" % 1000000000
'3b9aca00'
Short and sweet and easy: no base64 calculation, no hash function, no
database lookup, just a trivial int to string conversion.
--
Steven
More information about the Python-list
mailing list