views:

323

answers:

5

I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.

Would something like this work?

def genKey():
    hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
    alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
    return alnum_hash[:16]

What would be a good way to generate random numbers? If I base it on microtime, I have to account for the possibility of several calls of genKey() at the same time from different instances.

Or is there a better way to do all this?

Thanks.

+1  A: 

You can use this:

>>> import random
>>> ''.join(random.choice('0123456789ABCDEF') for i in range(16))
'E2C6B2E19E4A7777'

There is no guarantee that the keys generated will be unique so you should be ready to retry with a new key in the case the original insert fails. Also, you might want to consider using a deterministic algorithm to generate a string from an auto-incremented id instead of using random values, as this will guarantee you uniqueness (but it will also give predictable keys).

Mark Byers
random is not random but pseudo-random according to the documentation. Please use os.urandom instead.
prometheus
@prometheus. is `os.urandom` not psuedo-random?
aaronasterling
+3  A: 

Have a look at the uuid module (Python 2.5+).

A quick example:

>>> import uuid
>>> uid = uuid.uuid4()
>>> uid.hex
'df008b2e24f947b1b873c94d8a3f2201'
ChristopheD
This is 32 characters, and truncation of Guids is unsafe.
Brian
True (about the truncation). On the other hand: I'd just store 32 characters (unless you have a very specific reason to only store 16).
ChristopheD
A: 

This value is incremented by 1 on each call (it wraps around). Deciding where the best place to store the value will depend on how you are using it. You may find this explanation of interest, as it discusses not only how Guids work but also how to make a smaller one.

The short answer is this: Use some of those characters as a timestamp and the other characters as a "uniquifier," a value increments by 1 on each call to your uid generator.

Brian
A: 

i have an email address but i have the hash 32 character alphanumeric identifer how can i do it ..pease ... d57cc3fb90a1b2e16346af180a04e586

mark conorque
A: 

For random numbers a good source is os.urandom:

 >> import os
 >> import hashlib
 >> random_data = os.urandom(128)
 >> hashlib.md5(random_data).hexdigest()[:16]
rlotun