How to generate 10 digit unique-id in python?

问题描述 投票:0回答:2

我想在 python 中生成 10 位唯一标识。我尝试了以下方法,但没有人成功

  • get_random_string(10) -> 它生成具有碰撞概率的随机字符串
  • str(uuid.uuid4())[:10] -> 因为我只取前缀,所以它也有碰撞概率
  • sequential -> 我可以通过在前面加上 0 来生成唯一的顺序 ID,但它是顺序的并且更容易猜测。所以我想避免顺序 ids

我们有没有合适的系统来生成 10 位唯一 ID?

python django architecture unique-key
2个回答
-1
投票

尝试使用 模块这样:

import hashlib
import random

def generate_id():
    # Generate a random number
    random_num = str(random.randint(0, 99999999)).encode()

    # Generate a SHA-256 hash of the random number.
    hash_obj = hashlib.sha256(random_num)
    hex_digit = hash_obj.hexdigest()

    return hex_digit[:10]

-1
投票

您可以生成具有唯一值(例如当前时间和随机数)的 SHA-1 哈希。然后,可以提取hash的十六进制值的前10个字符,得到10位数字。

导入哈希库 随机导入 导入时间

def generate_unique_id():
    # Generate a unique value based on the current time and a random number
    unique_value = str(time.time()) + str(random.randint(0, 9999999999))
    
    # Hash the unique value using SHA-1
    sha1 = hashlib.sha1(unique_value.encode('utf-8'))
    
    # Extract the first 10 characters of the hexadecimal representation of the hash
    unique_id = sha1.hexdigest()[:10]
    
    return unique_id

请注意,这种方法应该生成具有低碰撞概率的唯一 ID,但 不能保证没有碰撞。特别是,如果短时间内产生的唯一值的个数超过哈希函数的输出空间,就可能发生碰撞。

© www.soinside.com 2019 - 2024. All rights reserved.