El módulo uuid
en Python se utiliza para generar identificadores únicos universales (UUIDs). A continuación se muestran algunos ejemplos comunes de cómo usar este módulo.
Generación de UUIDs
Para generar un UUID en Python, importa el módulo uuid
y utiliza las funciones proporcionadas para crear diferentes versiones de UUIDs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import uuid # Generar un UUID basado en el tiempo uuid1 = uuid.uuid1() print("UUID basado en el tiempo:", uuid1) # Generar un UUID basado en el nombre uuid3 = uuid.uuid3(uuid.NAMESPACE_DNS, 'example.com') print("UUID basado en el nombre (MD5):", uuid3) # Generar un UUID aleatorio uuid4 = uuid.uuid4() print("UUID aleatorio:", uuid4) # Generar un UUID basado en el nombre usando SHA-1 uuid5 = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com') print("UUID basado en el nombre (SHA-1):", uuid5) |
En el código anterior:
uuid.uuid1()
genera un UUID basado en el tiempo y la dirección MAC del host.uuid.uuid3()
yuuid.uuid5()
generan UUIDs basados en nombres utilizando hashing (MD5 parauuid3
y SHA-1 parauuid5
).uuid.uuid4()
genera un UUID aleatorio.
Convertir UUID a String y Viceversa
También puedes convertir UUIDs a cadenas de texto y viceversa.
1 2 3 4 5 6 7 8 9 10 11 |
import uuid uuid4 = uuid.uuid4() # Convertir un UUID a una cadena uuid_str = str(uuid4) print("UUID como cadena:", uuid_str) # Convertir una cadena de UUID a un objeto UUID uuid_from_str = uuid.UUID(uuid_str) print("UUID desde cadena:", uuid_from_str) |
En el código anterior:
str(uuid4)
convierte el UUID a una cadena de texto.uuid.UUID(uuid_str)
convierte la cadena de vuelta a un objeto UUID.