Using UUID in Python

Python has a library named UUID (Universal Unique Identifier) to generate a random object of 128 bits. This library generates unique IDs based on the system time and the network address of the computer. The UUID object is immutable and it contains some functions to create various unique IDs.  UUID is used for many purposes, such as creating a unique random ID, an ID-based MAC address, cryptographic hash values, or random documents. This tutorial will show you how you can create different types of UUID libraries by using different UUID functions.

Example 1: Create UUID based on system time and MAC address

The following example shows the use of the uuid1() function of the uuid module to generate various UUID values and to read and print the different property values of the UUID object. A UID object is defined by calling the uuid1() method to generate a unique id based on the system time and MAC address. Next, the normally generated ID, the corresponding bytes value, the integer value, and the hex value of the ID are printed.  The version, fields, node, and time properties of the ID are then printed in the next part of the script.

#!/usr/bin/env python3
 
#Import uuid module
import uuid
 
# Create random id using uuid1()
UID = uuid.uuid1()
 
# Print the normal ID
print ("The normal value: ",UID)
# Print the byte ID
print ("The byte value: ",repr(UID.bytes))
# Print the integer ID
print ("The integer value: ",UID.int)
# Print the hex ID
print ("The hex value: ",UID.hex)
 
# Print the version number
print ("The version is :", UID.version)
# Print the field values
print ("The fields are: ", UID.fields)
# Print the MAC value in hex
print ("The node value is: ", hex(UID.node))
# Print the time value
print ("The time value is: ", UID.time)

Output

The following output will appear after running the script. The output shows that the default ID value was generated in hex format by separating the distinct parts with a hyphen. The last part of the ID value contains the MAC address, which will always be the same. The node property of the ID object contains the MAC address.

Example 2: Generate SHA-1 and MD5 values of the hostname using uuid3() and uuid5()

An important use of UUID is to create cryptographic hash values The. uuid3() and uuid5() functions of the uuid module are used to generate MD5 and SHA-1 values. In the following script, a tuple variable named hosts is declared with three valid URL addresses. The values of the tuple are iterated using the for loop. The MD5 and the SHA-1 values of each URL are then calculated and printed in each iteration of the loop.

#!/usr/bin/env python3
# import uuid module
import uuid
 
# Define of a tuple of three hostnames
hosts = ('www.linuxhint.com', 'www.google.com', 'https://ift.tt/3h6e9Zm')
 
# Iterate the values of the tuple using loop
for hostname in hosts:
  # Print the hostname
  print("Hostname: ",hostname)
  # Use uuid5() to get SHA-1 value
  print('\tThe SHA-1 value :', uuid.uuid5(uuid.NAMESPACE_DNS, hostname))
  # Use uuid3() to get MD5 value
  print('\tThe MD5 value   :', uuid.uuid3(uuid.NAMESPACE_DNS, hostname))

Output

The following output will appear after running the script.

Example 3: Create random numbers using uuid4()

If you wish to generate the UUID randomly, then you should use the uuid4() function of the uuid module. The following script will generate five UUIDs based on random values via the uuid4() method. The while loop is used here to call the uuid4() method five times and print the randomly generated UUID values.

#!/usr/bin/env python3
 
# import uuid module
import uuid
# Initialize the variable
i = 1
# Iterate the loop five times
while(i<6):
  # Generate a random number
  print("No-", i,' ', uuid.uuid4())
  # Increment the value by one
  i = i + 1

Output

The following output will appear after running the script. If you run the script multiple times, then it will generate different UUIDs at different times.

Example 4: Create sorted UUID from a list using UUID object

The following script shows how you can convert the items of a list into UUIDs and print the values after sorting. Here, the list_ids variable is declared with four list items, where each item value must be in valid UUID format. First, the original values of the list_ids are printed. Next, each item value of the list is converted into UUID using a loop in the try block. If the list_ids contains any item value that does not match the UUID format, then a ValueError exception will be generated, and an error message will be printed. If no error occurs at the time of conversion, then the converted UUIDs are sorted using the sort() method. Next, the sorted UUID values are printed using the for loop.

#!/usr/bin/env python3
# import uuid module
import uuid
 
# Create a list of IDs of valid format
list_Ids = [
  'a4f8dd97-c8be-345b-239e-8a68e6abf800',
  '673a5eaa-56c6-aaaa-bc45-4536cd9067ac',
  'dcbbaa88-5bf1-11dd-ab48-990ab200d674',
  '4567aabb-89ad-77ab-67ad-aaaccdd904ae'
]
 
# Print the list values using loop
print('\nThe values of  the list:')
for val in list_Ids:
  print (val)
 
# The values of list will be converted into uuids and sorted
try:
  uuids = [ uuid.UUID(s) for s in list_Ids ]
  uuids.sort()
  print('\nThe values of the sorted uuids:')
  for val in uuids:
    print (val)

except ValueError:
  # Print error message if any value of the list is in invalid format
  print('Badly formed hexadecimal UUID string')

Output

The following output will appear after running the script. Here, all the items in the list are in the correct UUID format. So, no ValueError will be generated. The first part of the output printed the original list items, and the second part of the output printed the sorted values of the UUIDs.

Conclusion

You may be required to generate UUID in Python for various programming purposes. This tutorial showed you how to generate various UUIDs using a variety of methods. After reading this article and practicing the included examples, you should be able to create UUIDs according to your programming needs.



from Linux Hint https://ift.tt/3dDqEtb

Post a Comment

0 Comments