Como criar um GUID / UUID em Python
Como faço para criar um GUID em Python que seja independente da plataforma? Ouvi dizer que há um método usando Ativepython no Windows, mas é Windows apenas porque ele usa COM. Existe um método para usar Python simples?
5 answers
O módulo uuid, no Python 2.5 e up, oferece UUID compatível com o RFC geracao. Veja o módulo docs e o RFC para mais detalhes. [Fonte]
Docs:
- Python 2: http://docs.python.org/2/library/uuid.html
- Python 3: https://docs.python.org/3/library/uuid.html
Exemplo (a trabalhar em 2 e 3):
>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'
Se estiver a usar o Python 2. 5 ou mais tarde, o Módulo uuid já está incluído na distribuição padrão Python.
Ex:
>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
Copiado de: https://docs.python.org/2/library/uuid.html (Uma vez que as ligações publicadas não estavam activas e continuam a ser actualizadas)
>>> 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')
Uso os GUIDs como chaves aleatórias para Operações do tipo de base de dados.
{[[2]} a forma hexadecimal, com os traços e caracteres extra, parecem-me desnecessariamente longos. Mas eu também gosto que strings representando números hexadecimais são muito seguros em que eles não contêm caracteres que podem causar problemas em algumas situações, como'+','=', etc..Em vez de hexadecimal, eu uso um texto Base64 url-safe. O seguinte não está em conformidade com qualquer especificação UUID/GUID embora (com excepção de ter a quantidade necessária de aleatoriedade).
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('=', '')
Esta função é totalmente configurável e gera um uid único com base no formato indicado
Eg:- [8, 4, 4, 4, 12] , Este é o formato mencionado e irá gerar o seguinte 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