Quick Start: Generate Random UUID with uuid4()
The fastest and most common way to generate a UUID in Python is using uuid4(), which creates a random UUID based on cryptographically secure random numbers. This method is perfect for generating unique identifiers for database records, session tokens, or any application requiring unique IDs.
Standard Library - No Installation Needed
Built-inimport uuid
# Generate random UUID v4
my_uuid = uuid.uuid4()
print(my_uuid)
# Output: 550e8400-e29b-41d4-a716-446655440000
# Get as string
uuid_str = str(my_uuid)
# Generate multiple UUIDs
uuids = [uuid.uuid4() for _ in range(5)]
for u in uuids:
print(u)
✓ Advantages
- • No external dependencies
- • Cryptographically secure
- • Fast generation
- • Cross-platform compatible
Use Cases
- • Database primary keys
- • API request tracking
- • Session identifiers
- • File naming
All UUID Versions: Complete Python Implementation
Python's uuid module supports four different UUID versions, each designed for specific use cases. UUID v1 includes timestamps and MAC addresses, v3 and v5 create deterministic hashes, while v4 generates random UUIDs. Choose the right version based on your requirements for uniqueness, reproducibility, or sortability.
UUID v4 - Random (Recommended)
MOST COMMONGenerates random UUIDs using cryptographically secure random numbers. Best for general-purpose unique identifiers.
uuid4_id = uuid.uuid4() print(uuid4_id) # 550e8400-e29b-41d4-a716-446655440000
UUID v1 - Timestamp + MAC Address
TIME-BASEDIncludes timestamp and MAC address. Sortable by creation time but may expose hardware info.
uuid1_id = uuid.uuid1() print(uuid1_id) # 6ba7b810-9dad-11d1-80b4-00c04fd430c8
UUID v5 - SHA-1 Hash (Deterministic)
REPRODUCIBLECreates UUIDs from namespace and name using SHA-1. Same inputs always produce the same UUID.
namespace = uuid.NAMESPACE_DNS uuid5_id = uuid.uuid5(namespace, 'example.com') print(uuid5_id) # Always the same for this input
UUID v3 - MD5 Hash
LEGACYSimilar to v5 but uses MD5 instead of SHA-1. Use v5 for new applications.
uuid3_id = uuid.uuid3(uuid.NAMESPACE_DNS, 'example.com')
UUID Conversion and String Formatting in Python
Python's UUID objects can be converted to various formats including strings, integers, bytes, and hex representations. Understanding these conversion methods is essential for database storage, API responses, and interoperability with other systems.
import uuid
my_uuid = uuid.uuid4()
# String formats
str_uuid = str(my_uuid) # '550e8400-e29b-41d4-a716-446655440000'
hex_uuid = my_uuid.hex # '550e8400e29b41d4a716446655440000' (no hyphens)
urn_uuid = my_uuid.urn # 'urn:uuid:550e8400-e29b-41d4-a716-446655440000'
# Integer representation (128-bit)
int_uuid = my_uuid.int
print(f"As int: {int_uuid}")
# Bytes (16 bytes)
bytes_uuid = my_uuid.bytes
print(f"As bytes: {bytes_uuid}")
# Fields (breakdown)
print(f"Time low: {my_uuid.time_low}")
print(f"Time mid: {my_uuid.time_mid}")
print(f"Version: {my_uuid.version}")
print(f"Variant: {my_uuid.variant}")
# Uppercase formatting
upper_uuid = str(my_uuid).upper()
Parse and Validate UUID Strings in Python
Validating UUIDs from user input or external sources is crucial for data integrity. Python provides multiple methods to parse and validate UUID strings, with proper error handling to ensure your application handles invalid inputs gracefully.
Parse UUID
# Parse from string
uuid_obj = uuid.UUID('550e8400-e29b-41d4-a716-446655440000')
# From hex (no hyphens)
uuid_hex = uuid.UUID(hex='550e8400e29b41d4a716446655440000')
# From bytes
uuid_bytes = uuid.UUID(bytes=b'...')
# From integer
uuid_int = uuid.UUID(int=12345678...)
Validation Function
def is_valid_uuid(uuid_string):
try:
uuid.UUID(uuid_string)
return True
except ValueError:
return False
# Test
print(is_valid_uuid('550e8400-e29b-41d4-a716-446655440000')) # True
print(is_valid_uuid('invalid')) # False
Django Models: UUID Primary Keys Integration
Django provides excellent support for UUID primary keys through the UUIDField. Using UUIDs instead of auto-incrementing integers offers better security by hiding sequential patterns and enables easier data merging across distributed systems.
Django Best Practices
Use UUIDField with default=uuid.uuid4 for automatic UUID generation. Always use uuid.uuid4 (without parentheses) as the callable, not uuid.uuid4() which would generate the same UUID for all records.
from django.db import models
import uuid
class Article(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4, # Callable, not uuid.uuid4()
editable=False
)
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.title
# Usage
article = Article.objects.create(
title="My Article",
content="Article content here"
)
print(article.id) # Automatically generated UUID
Flask Application UUID Route Parameters
Flask supports UUID route parameters natively, making it easy to create RESTful APIs with UUID-based resource identifiers. This ensures type-safe routing and automatic validation of UUID formats in your URL paths.
from flask import Flask, jsonify
import uuid
app = Flask(__name__)
# UUID as route parameter
@app.route('/users/', methods=['GET'])
def get_user(user_id):
# user_id is automatically parsed as UUID object
print(type(user_id)) #
# Fetch user from database
user = {
'id': str(user_id),
'name': 'John Doe',
'email': 'john@example.com'
}
return jsonify(user)
@app.route('/users', methods=['POST'])
def create_user():
user_id = uuid.uuid4()
# Save to database
user = {
'id': str(user_id),
'name': 'New User'
}
return jsonify(user), 201
if __name__ == '__main__':
app.run(debug=True)
SQLAlchemy UUID Column Type Configuration
SQLAlchemy supports UUID columns across different database backends including PostgreSQL, MySQL, and SQLite. The implementation varies by database - PostgreSQL has native UUID support while others store UUIDs as strings or binary data.
from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import UUID as pgUUID
import uuid
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
# PostgreSQL native UUID
id = Column(pgUUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
# For other databases (MySQL, SQLite) - use String
# id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
name = Column(String(100))
email = Column(String(255), unique=True)
# Create engine
engine = create_engine('postgresql://user:pass@localhost/dbname')
Base.metadata.create_all(engine)
# Usage
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
new_user = User(name='Alice', email='alice@example.com')
session.add(new_user)
session.commit()
print(new_user.id) # Auto-generated UUID