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?
You can use this:
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).
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.
simply use python inbuilt uuid :
Simply use python builtin uuid:
If UUIDs are okay for your purposes use the built in uuid package.
One Line Solution:
As none of the answers provide you with a random string consisting of characters 0-9, a-z, A-Z: Here is a working solution which will give you approx. 4.5231285e+74 keys:
It is also very readable without knowing ASCII codes by heart.
There is an even shorter version since
python 3.6.2
: