ChatGPT解决这个技术问题 Extra ChatGPT

如何在 Python 中创建 GUID/UUID

如何在 Python 中创建独立于平台的 GUID?我听说有一种在 Windows 上使用 ActivePython 的方法,但它只是 Windows,因为它使用 COM。有没有使用普通 Python 的方法?

对于所有神圣事物的热爱,它是一个 UUID - 通用唯一 ID en.wikipedia.org/wiki/Universally_unique_identifier - 不幸的是,MS 更喜欢 GUID。
这是一个适合您的班轮:python -c 'import uuid; print(uuid.uuid4())'
我认为 GUID 比 UUID 更有意义,因为 global 意味着在某个命名空间内是全局的,而 universal 似乎声称真正的普遍唯一性。无论如何,我们都知道我们在这里谈论的是什么。

s
stuartd

uuid 模块提供不可变的 UUID 对象(UUID 类)和函数 uuid1()、uuid3()、uuid4()、uuid5(),用于生成 RFC 4122 中指定的版本 1、3、4 和 5 UUID。

如果您只需要一个唯一的 ID,您可能应该调用 uuid1() 或 uuid4()。请注意,uuid1() 可能会损害隐私,因为它会创建一个包含计算机网络地址的 UUID。 uuid4() 创建一个随机的 UUID。

UUID 版本 6 和 7 - 用于现代应用程序和数据库的新通用唯一标识符 (UUID) 格式 (draft) rfc - 可从 https://pypi.org/project/uuid6/

文件:

蟒蛇2

蟒蛇 3

示例(适用于 Python 2 和 3):

>>> import uuid

>>> # make a random UUID
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')

>>> # Convert a UUID to a string of hex digits in standard form
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'

>>> # Convert a UUID to a 32-character hexadecimal string
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'

另外,请查看我编写的 shortuuid 模块,因为它允许您生成更短、可读的 UUID:github.com/stochastic-technologies/shortuuid
@StavrosKorokithakis:你有没有为 Python 3.x 编写过 shortuuid 模块?
@JayPatel shortuuid 是否不适用于 Python 3?如果没有,请提交一个错误。
uuid4().hexstr(uuid4()) 有什么区别?
好吧,正如您在上面看到的,str(uuid4()) 返回 UUID 的字符串表示形式,其中包含破折号,而 uuid4().hex 返回 "The UUID as a 32-character hexadecimal string"
j
jesterjunk

如果您使用的是 Python 2.5 或更高版本,则 uuid module 已包含在 Python 标准分发中。

前任:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')

u
user5994461

复制自:https://docs.python.org/3/library/uuid.html(因为发布的链接不活跃并且不断更新)

>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

>>> # get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')

C
Chris Dutrow

我使用 GUID 作为数据库类型操作的随机键。

带有破折号和额外字符的十六进制形式对我来说似乎不必要地长。但我也喜欢表示十六进制数字的字符串非常安全,因为它们不包含在某些情况下可能导致问题的字符,例如“+”、“=”等。

我使用 url 安全的 base64 字符串而不是十六进制。以下不符合任何 UUID/GUID 规范(除了具有所需的随机性)。

import base64
import uuid

# get a UUID - URL safe, Base64
def get_a_uuid():
    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
    return r_uuid.replace('=', '')

如果您不想在任何 UUID 上下文中使用它,您也可以使用 random.getrandbits(128).to_bytes(16, 'little') 或(用于加密随机性)os.urandom(16) 并获得完整的 128 位随机数(UUIDv4 在版本上使用 6-7 位信息)。或仅使用 15 个字节(丢失 1-2 位随机与 UUIDv4)并避免需要修剪 = 符号,同时还将编码大小减少到 20 个字节(从 24,修剪到 22),作为任何倍数3 个字节编码为 #bytes / 3 * 4 个 base64 字符,无需填充。
@ShadowRanger 是的,这基本上就是这个想法。 128 个随机位,尽可能短,同时也是 URL 安全的。理想情况下,它只会使用大写和小写字母,然后是数字。所以我猜是一个base-62字符串。
当我使用你的函数时,我从 return 语句中得到一个类型错误,需要一个类似字节的对象。它可以用 return str(r_uuid).replace('=','') 修复。
M
Mobasshir Bhuiya

如果您需要为模型或唯一字段的主键传递 UUID,则下面的代码将返回 UUID 对象 -

 import uuid
 uuid.uuid4()

如果您需要将 UUID 作为 URL 的参数传递,您可以执行以下代码 -

import uuid
str(uuid.uuid4())

如果您想要 UUID 的十六进制值,您可以执行以下操作 -

import uuid    
uuid.uuid4().hex

S
SaddamBinSyed

如果您正在制作一个网站或应用程序,您每次都需要一个唯一的 ID。它应该是一个数字字符串,然后 UUID 是 python 中的一个很棒的包,它有助于创建一个唯一的 id。

**pip install uuid**

import uuid

def get_uuid_id():
    return str(uuid.uuid4())

print(get_uuid_id()) 

输出示例:89e5b891-cf2c-4396-8d1c-49be7f2ee02d


M
Mitch McMabers

2019 年答案(适用于 Windows):

如果您想要一个在 Windows 上唯一标识机器的永久 UUID,您可以使用这个技巧:(复制自我在 https://stackoverflow.com/a/58416992/8874388 的答案)。

from typing import Optional
import re
import subprocess
import uuid

def get_windows_uuid() -> Optional[uuid.UUID]:
    try:
        # Ask Windows for the device's permanent UUID. Throws if command missing/fails.
        txt = subprocess.check_output("wmic csproduct get uuid").decode()

        # Attempt to extract the UUID from the command's result.
        match = re.search(r"\bUUID\b[\s\r\n]+([^\s\r\n]+)", txt)
        if match is not None:
            txt = match.group(1)
            if txt is not None:
                # Remove the surrounding whitespace (newlines, space, etc)
                # and useless dashes etc, by only keeping hex (0-9 A-F) chars.
                txt = re.sub(r"[^0-9A-Fa-f]+", "", txt)

                # Ensure we have exactly 32 characters (16 bytes).
                if len(txt) == 32:
                    return uuid.UUID(txt)
    except:
        pass # Silence subprocess exception.

    return None

print(get_windows_uuid())

使用 Windows API 获取计算机的永久 UUID,然后处理字符串以确保它是有效的 UUID,最后返回一个 Python 对象 (https://docs.python.org/3/library/uuid.html),它为您提供了使用数据的便捷方式(例如 128 位整数、十六进制字符串等)。

祝你好运!

PS:子进程调用可能会替换为直接调用 Windows 内核/DLL 的 ctypes。但就我的目的而言,这个功能就是我所需要的。它进行强大的验证并产生正确的结果。


S
SMMH

运行此命令:

pip install uuid uuid6

然后运行您可以从 uuid 包中导入 uuid1uuid3uuid4uuid5 函数,以及从 uuid6 包中导入 uuid6uuid7 函数。

调用每个函数的示例输出如下(需要参数的 uuid3uuid5 除外):

>>> import uuid, uuid6
>>> print(*(str(i()) for i in [uuid.uuid1, uuid.uuid4, uuid6.uuid6, uuid6.uuid7]), sep="\n")
646e934b-f20c-11ec-ad9f-54a1500ef01b
560e2227-c738-41d9-ad5a-bbed6a3bc273
1ecf20b6-46e9-634b-9e48-b2b9e6010c57
01818aa2-ec45-74e8-1f85-9d74e4846897

M
Manoj Selvin

此函数是完全可配置的,并根据指定的格式生成唯一的 uid

例如:- [8, 4, 4, 4, 12] ,这是提到的格式,它将生成以下 uuid

LxoYNyXe-7hbQ-caJt-DSdU-PDAht56cMEWi

 import random as r

 def generate_uuid():
        random_string = ''
        random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        uuid_format = [8, 4, 4, 4, 12]
        for n in uuid_format:
            for i in range(0,n):
                random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
            if n != 12:
                random_string += '-'
        return random_string

UUID 是标准的,长度不可变。在某些情况下,以可配置的方式生成随机字符串可能很有用,但在这种情况下则不然。您可以检查 en.wikipedia.org/wiki/Universally_unique_identifier 的定义。
最好避免使用这个,否则您可能会遇到兼容性问题(这些不是标准 GUID)
此外,甚至不能远程保证是唯一的。它可能是随机的,但不是唯一的。
@regretoverflow 没有 GUID 是独一无二的,只是如此庞大以至于极不可能发生碰撞。
GUID 是一个非常长的数字的字符串表示形式,因此“LxoYNyXe ...”不会插入。
Q
QtRoS

检查this帖子,对我帮助很大。简而言之,对我来说最好的选择是:

import random 
import string 

# defining function for random 
# string id with parameter 
def ran_gen(size, chars=string.ascii_uppercase + string.digits): 
    return ''.join(random.choice(chars) for x in range(size)) 

# function call for random string 
# generation with size 8 and string  
print (ran_gen(8, "AEIOSUMA23")) 

因为我只需要 4-6 个随机字符而不是笨重的 GUID。


这似乎与关于 UUID 的问题完全无关。