我如何在Python中创建一个平台独立的GUID/UUID ?我听说在Windows上有一个使用ActivePython的方法,但它只是Windows,因为它使用COM。是否有使用纯Python的方法?
当前回答
我使用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('=', '')
其他回答
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
此函数完全可配置,并根据指定的格式生成唯一的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
复制自: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('=', '')
推荐文章
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 滚动或滑动窗口迭代器?
- python的方法找到最大值和它的索引在一个列表?
- 如何读取文件的前N行?
- 如何删除matplotlib中的顶部和右侧轴?
- 解析.py文件,读取AST,修改它,然后写回修改后的源代码
- Visual Studio Code:如何调试Python脚本的参数
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc
- 结合conda环境。Yml和PIP requirements.txt
- 将命名元组转换为字典
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件