如何在 Python 中创建独立于平台的 GUID?我听说有一种在 Windows 上使用 ActivePython 的方法,但它只是 Windows,因为它使用 COM。有没有使用普通 Python 的方法?
python -c 'import uuid; print(uuid.uuid4())'
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'
如果您使用的是 Python 2.5 或更高版本,则 uuid module 已包含在 Python 标准分发中。
前任:
>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
复制自: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')
我使用 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 个字节(丢失 1-2 位随机与 UUIDv4)并避免需要修剪 =
符号,同时还将编码大小减少到 20 个字节(从 24,修剪到 22),作为任何倍数3 个字节编码为 #bytes / 3 * 4
个 base64 字符,无需填充。
return
语句中得到一个类型错误,需要一个类似字节的对象。它可以用 return str(r_uuid).replace('=','')
修复。
如果您需要为模型或唯一字段的主键传递 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
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。但就我的目的而言,这个功能就是我所需要的。它进行强大的验证并产生正确的结果。
运行此命令:
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
此函数是完全可配置的,并根据指定的格式生成唯一的 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
检查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。
不定期副业成功案例分享
shortuuid
模块,因为它允许您生成更短、可读的 UUID:github.com/stochastic-technologies/shortuuiduuid4().hex
和str(uuid4())
有什么区别?str(uuid4())
返回 UUID 的字符串表示形式,其中包含破折号,而uuid4().hex
返回 "The UUID as a 32-character hexadecimal string"