Efficiently generate a 16-character, alphanumeric

2019-01-30 13:50发布

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?

8条回答
放荡不羁爱自由
2楼-- · 2019-01-30 14:33

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).

查看更多
小情绪 Triste *
3楼-- · 2019-01-30 14:37
>>> import random
>>> ''.join(random.sample(map(chr, range(48, 57) + range(65, 90) + range(97, 122)), 16))
'CDh0geq3NpKtcXfP'
查看更多
女痞
4楼-- · 2019-01-30 14:39

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.

查看更多
forever°为你锁心
5楼-- · 2019-01-30 14:40

simply use python inbuilt uuid :

import uuid
print uuid.uuid4().hex[:16].upper()
查看更多
走好不送
6楼-- · 2019-01-30 14:40

Simply use python builtin uuid:

If UUIDs are okay for your purposes use the built in uuid package.

One Line Solution:

>>> import uuid
>>> str(uuid.uuid4().get_hex().upper()[0:16])
'40003A9B8C3045CA'
查看更多
Anthone
7楼-- · 2019-01-30 14:53

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:

import random, string
x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(16))
print(x)

It is also very readable without knowing ASCII codes by heart.

There is an even shorter version since python 3.6.2:

import random, string
x = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
print(x)
查看更多
登录 后发表回答