如何在 Python 中创建 GUID/UUID
- 2025-01-09 08:46:00
- admin 原创
- 83
问题描述:
如何在 Python 中创建独立于平台的 GUID/UUID?我听说有一种在 Windows 上使用 ActivePython 的方法,但它仅适用于 Windows,因为它使用 COM。有没有使用纯 Python 的方法?
解决方案 1:
uuid 模块提供不可变的 UUID 对象(UUID 类)和函数
uuid1()
、uuid3()
、uuid4()
,用于生成RFC 4122uuid5()
中指定的版本 1、3、4 和 5 的 UUID 。
如果您想要的只是一个唯一的 ID,您可能应该致电
uuid1()
或uuid4()
。请注意,这
uuid1()
可能会危及隐私,因为它会创建一个包含计算机网络地址的 UUID。
uuid4()
创建一个随机 UUID。
UUID 版本 6、7 和 8 -用于现代应用程序和数据库密钥的新型通用唯一标识符 (UUID) 格式- (草案) rfc - 可从https://pypi.org/project/uuid6/获取
文档:
Python 2
Python 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'
解决方案 2:
如果您使用的是 Python 2.5 或更高版本,则uuid 模块已包含在 Python 标准发行版中。
前任:
>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
解决方案 3:
我使用 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('=', '')
解决方案 4:
如果你需要传递 UUID 作为模型或唯一字段的主键,那么下面的代码将返回 UUID 对象 -
import uuid
uuid.uuid4()
如果需要将 UUID 作为 URL 参数传递,可以按照以下代码进行操作 -
import uuid
str(uuid.uuid4())
如果您想要 UUID 的十六进制值,可以执行以下操作 -
import uuid
uuid.uuid4().hex
解决方案 5:
如果您正在制作一个网站或应用程序,每次都需要一个唯一的 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
解决方案 6:
运行此命令:
pip install uuid uuid6
然后运行,您可以从包中导入uuid1
、uuid3
和函数,以及从包中uuid4
导入和函数。uuid5
`uuiduuid6
uuid7`uuid6
调用每个函数的示例输出如下(除了需要参数的uuid3
和uuid5
):
>>> import uuid, uuid6
>>> print(*(str(i()) for i in [uuid.uuid1, uuid.uuid4, uuid6.uuid6, uuid6.uuid7]), sep="
")
646e934b-f20c-11ec-ad9f-54a1500ef01b
560e2227-c738-41d9-ad5a-bbed6a3bc273
1ecf20b6-46e9-634b-9e48-b2b9e6010c57
01818aa2-ec45-74e8-1f85-9d74e4846897
解决方案 7:
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"UUID[s
]+([^s
]+)", 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:子进程调用可能可以用 ctypes 直接调用 Windows 内核/DLL 来代替。但就我的目的而言,这个函数就是我所需要的。它进行强大的验证并产生正确的结果。
解决方案 8:
此功能完全可配置,并根据指定的格式生成唯一的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