Appearance
Generate UUID in Python
Python offers UUID generation in its standard library
python
import uuid
# generate UUID version 1 - time based
uuid.uuid1()
# generate UUID version 3 - deterministic and hashed with MD5
uuid.uuid3(uuid.uuid4(), "name")
# generate UUID version 4 - random
uuid.uuid4()
# generate UUID version 5 - deterministic and hashed with SHA-1
uuid.uuid5(uuid.uuid4(), "name")
Advanced Python Usage
UUID Utility Functions:
python
import uuid
import re
def generate_uuid_v4():
"""Generate a random UUID version 4"""
return str(uuid.uuid4())
def generate_deterministic_uuid(name, namespace=None):
"""Generate deterministic UUID v5 from name"""
if namespace is None:
namespace = uuid.NAMESPACE_URL
return str(uuid.uuid5(namespace, name))
def is_valid_uuid(uuid_string):
"""Validate UUID format"""
uuid_pattern = re.compile(
r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
re.IGNORECASE
)
return bool(uuid_pattern.match(uuid_string))
def get_uuid_version(uuid_string):
"""Get UUID version from string"""
try:
uuid_obj = uuid.UUID(uuid_string)
return uuid_obj.version
except ValueError:
return None
Django Integration:
python
# models.py
import uuid
from django.db import models
class User(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100)
email = models.EmailField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.name} ({self.id})"
Flask API Example:
python
from flask import Flask, jsonify
import uuid
from datetime import datetime
app = Flask(__name__)
@app.route('/api/uuid')
def generate_uuid():
return jsonify({
'uuid': str(uuid.uuid4()),
'timestamp': datetime.now().isoformat()
})
@app.route('/api/uuid/<name>')
def generate_named_uuid(name):
return jsonify({
'uuid': str(uuid.uuid5(uuid.NAMESPACE_URL, name)),
'name': name,
'deterministic': True
})
UUID Version Comparison
Choose the right version for your Python application:
- Version 1 - Time-based, includes MAC address
- Version 3 - MD5 namespace-based, deterministic
- Version 4 - Random, most popular choice
- Version 5 - SHA-1 namespace-based, more secure than v3
- Version 6 - Time-ordered, better than v1 for databases
- Version 7 - Modern time-based with improved sorting
For Python applications:
- Django models: Use Version 4 for primary keys
- Data processing: Consider Version 5 for deterministic IDs
- Time-series data: Use Version 7 for chronological ordering
How do I generate UUID in other languages?
Web development languages:
- JavaScript - crypto.randomUUID() & uuid library
- TypeScript - Type-safe UUID generation
- PHP - Laravel and Symfony frameworks
Systems programming: