我如何在Python中创建一个平台独立的GUID/UUID ?我听说在Windows上有一个使用ActivePython的方法,但它只是Windows,因为它使用COM。是否有使用纯Python的方法?
当前回答
2019答案(适用于Windows):
如果你想要一个永久的UUID,在Windows上唯一地标识一台机器,你可以使用这个技巧:(复制自我在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所取代。但对于我的目的,这个函数就是我所需要的。它能进行强有力的验证并产生正确的结果。
其他回答
如果您需要为您的模型或唯一字段的主键传递UUID,那么下面的代码将返回UUID对象-
import uuid
uuid.uuid4()
如果你需要传递UUID作为URL的参数,你可以像下面的代码-
import uuid
str(uuid.uuid4())
如果你想要一个UUID的十六进制值,你可以做下面一个-
import uuid
uuid.uuid4().hex
如果你正在制作一个网站或应用程序,你需要每次一个唯一的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
此函数完全可配置,并根据指定的格式生成唯一的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
执行如下命令:
pip install uuid uuid6
然后运行你可以从uuid包中导入uuid1, uuid3, uuid4和uuid5函数,从uuid6包中导入uuid6和uuid7函数。
调用这些函数的输出示例如下(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
如果您使用的是Python 2.5或更高版本,则uuid模块已经包含在Python标准发行版中。
Ex:
>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')