如何创建一个GUID/usb驱Python
-
22-08-2019 - |
题
我如何创建一个GUID在蟒蛇,是独立于平台的?我听说还有一个方法是使用ActivePython在窗口,但它是Windows只是因为它使用COM.是否有一个方法使用普通蟒蛇?
解决方案
该usb驱模块,在Python2.5并起来,提供RFC符合usb驱 代。参见模块文件和RFC的详细信息。[来源]
文档:
例(工作月2日和3):
>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'
其他提示
如果你使用Python2.5或后, usb驱模块 已经包含与蟒蛇的标准分配。
例如:
>>> 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作为数据库类型的操作的随机密钥。
在十六进制形式,用短划线和多余的字符似乎不必要的长我。不过,我也很喜欢,代表十六进制数字符串是在非常安全的,他们不包含可能会导致在某些情况下,如“+”,“=”,等等。
问题字符除了十六进制的,我用的网址安全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
如果您需要通过UUID为您的模型或再下面的代码独特领域的主键返回UUID对象 -
import uuid
uuid.uuid4()
如果您需要通过UUID作为URL参数,你可以像下面的代码 -
import uuid
str(uuid.uuid4())
如果你想为一个UUID的十六进制值,你可以做下面的一个 -
import uuid
uuid.uuid4().hex
不隶属于 StackOverflow