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?
Have a look at the uuid module (Python 2.5+).
A quick example:
Note that the OP asked for a 16-character alphanumeric string, but UUID4 strings are 32 characters long. You should not truncate this string, instead, use the complete 32 characters.
For random numbers a good source is
os.urandom
: