如何在 Python 中创建一个平台无关的 GUID/UUID?我听说有一种方法可以使用 Windows 上的 ActivePython,但它仅适用于 Windows,因为它使用了 COM。是否有一种方法可以使用纯 Python 实现?
如何在 Python 中创建一个平台无关的 GUID/UUID?我听说有一种方法可以使用 Windows 上的 ActivePython,但它仅适用于 Windows,因为它使用了 COM。是否有一种方法可以使用纯 Python 实现?
uuid1()
,uuid3()
,uuid4()
,uuid5()
用于生成符合RFC 4122规定的版本1、3、4和5的UUID。>>> 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:https://github.com/stochastic-technologies/shortuuid - Stavros Korokithakisuuid4().hex
和str(uuid4())
之间的区别是前者返回UUID对象的16进制字符串表示,后者返回UUID对象的常规字符串表示。 - Kevinstr(uuid4())
返回包含破折号的UUID字符串表示形式,而uuid4().hex
返回“UUID作为32字符十六进制字符串”的形式。 - stuartd>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
我使用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('=', '')
random.getrandbits(128).to_bytes(16, 'little')
或(用于加密随机性)os.urandom(16)
,以获得完整的128位随机数(UUIDv4在版本信息上使用6-7位)。或者只使用15个字节(与UUIDv4相比,失去1-2位随机性),避免需要修剪掉“=”符号,并将编码大小减小到20个字节(从24个字节减小到22个字节),因为任何3个字节的倍数都可编码为#bytes / 3 * 4
个base64字符,无需填充。 - ShadowRangerreturn
语句中得到一个类型错误,期望一个类似于字节的对象。可以通过return str(r_uuid).replace('=','')
来修复它。 - Mark Kortink import uuid
uuid.uuid4()
如果您需要将UUID作为URL参数传递,可以像下面的代码一样操作 -import uuid
str(uuid.uuid4())
如果您想要获取 UUID 的十六进制值,可以执行下面的操作 -
import uuid
uuid.uuid4().hex
**pip install uuid**
import uuid
def get_uuid_id():
return str(uuid.uuid4())
print(get_uuid_id())
输出示例: 89e5b891-cf2c-4396-8d1c-49be7f2ee02d
pip install uuid uuid6
接下来你可以导入uuid1
、uuid3
、uuid4
和uuid5
函数从uuid
包中,以及uuid6
和uuid7
函数从uuid6
包中。
调用这些函数的示例输出如下(除了需要参数的uuid3
和uuid5
):
>>> 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
2019年的答案(适用于Windows):
如果您想要一个在Windows上唯一标识机器的永久UUID,您可以使用这个技巧:(从我的回答https://dev59.com/YXE95IYBdhLWcg3wGZ9_#58416992中复制)。
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())
这个函数是完全可配置的,它根据指定的格式生成唯一的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
python -c 'import uuid; print(uuid.uuid4())'
它会生成一个UUID并将其打印出来。 - Ctrl-C