如何在Python中创建独立于平台的GUID?我听说有一种方法在Windows上使用ActivePython,但它只是Windows,因为它使用COM。有没有使用普通Python的方法?
Python 2.5及更高版本中的uuid模块提供符合RFC的UUID生成。有关详细信息,请参阅模块文档和RFC。 [source]
文档:
示例(处理2和3):
>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'
如果您使用的是Python 2.5或更高版本,则uuid module已包含在Python标准发行版中。
例如:
>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
复制自:https://docs.python.org/2/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-safe 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('=', '')
此功能是完全可配置的,并根据指定的格式生成唯一的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