UUID (Universally Unique Identifier) is a standard for uniquely identifying information. Python provides a simple method to generate UUID, which is very useful in application scenarios that require a unique identifier. For example, generating unique user IDs, session IDs, etc. The following is a detailed description of how to generate UUID using Python.
Use the uuid module to generate UUID
Python's standard library uuid
module can be used to generate various types of UUIDs. The following is a sample code that demonstrates how to generate a UUID:
import uuid
namespace_uuid = uuid.NAMESPACE_DNS
name = "perfcode.com"
uuidv1 = uuid.uuid1()
print(uuidv1)
uuidv3 = uuid.uuid3(namespace_uuid,name)
print(uuidv3)
uuidv4 = uuid.uuid4()
print(uuidv4)
uuidv5 = uuid.uuid5(namespace_uuid, name)
print(uuidv5)
Program running results
7f30a571-6d14-11ef-8488-8cc6814e827e 64672e25-0622-30f3-bf57-d30f5ac6c97c 74a596b3-ce42-4e34-a40a-b92d24d9c650 f450f82e-d7c6-5ca8-a793-7686224e98c1
UUID Versions
There are currently 5 versions of UUID, each with a different generation method:
- UUIDv1: Generated based on timestamp and MAC address;
- UUIDv2: UUID generation based on DCE security;
- UUIDv3: Generated based on MD5 hash value of namespace and name;
- UUIDv4: Generated based on random numbers;
- UUIDv5: Generated based on SHA-1 hash value of namespace and name.
It should be noted that Python does not have a built-in uuid.uuid2()
function;