Stop Using Random Strings! Generate Unique IDs with Python’s UUID – System-Wide Uniqueness for Large Projects!

😩 Have you encountered these issues?

  • Writing scripts to temporarily save data, worried about filename duplication?
  • Need to generate a unique ID for user registration, but handwritten logic is long and clunky?
  • Want to assign a unique number to each task, but afraid of conflicts?

Stop using <span>time.time()</span> and <span>random.randint()</span> to concatenate strings! Python has a built-in tool <span>uuid</span> that can do it in one line:

🎯 Article Objective

Master the common generation methods of the <span>uuid</span> module + practical application scenarios including file naming, user ID generation, database primary keys, task tracking, etc.!

βœ… Core Usage: What are the ways to generate unique IDs?

import uuid

print(uuid.uuid1())  # Generated based on host + timestamp
print(uuid.uuid4())  # Completely random (commonly used)
print(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com"))  # Based on name hash

Example output:

f8e0e8c0-7a57-11ee-a4f0-4c0b2f7d2ad3
38a4f63a-3be2-48fd-bc13-81a973e51c6b
886313e1-3b8a-5372-9b90-0c9aee199e5d

πŸ›  Practical Scenario #1: Automatically naming uploaded files to prevent duplication

import uuid
import os

def save_file_with_uuid(content, folder="uploads"):
    os.makedirs(folder, exist_ok=True)
    filename = f"{uuid.uuid4().hex}.txt"  # hex is the pure ID without "-"
    path = os.path.join(folder, filename)
    with open(path, 'w') as f:
        f.write(content)
    return path

# Example usage
print(save_file_with_uuid("hello world"))

βœ… Unique filenames, no risk of overwritingβœ… Using <span>.hex</span> string is more suitable for filenames (no “-“)

πŸ›  Practical Scenario #2: Generating unique IDs for user registration

import uuid

def register_user(name):
    user_id = str(uuid.uuid4())
    print(f"βœ… User {name}'s ID is {user_id}")
    return {"id": user_id, "name": name}

register_user("Alice")

You can also choose <span>uuid5</span> to bind to email, phone number, etc., allowing the same username to generate the same ID:

uuid.uuid5(uuid.NAMESPACE_DNS, "[email protected]")

πŸ›  Practical Scenario #3: Generating tracking IDs for tasks or logs

def log_with_uuid(message):
    trace_id = uuid.uuid4()
    print(f"[{trace_id}] {message}")

log_with_uuid("Starting order processing")
log_with_uuid("Inventory check completed")

βœ… Traceable, debuggable, and logs are queryable

πŸ›  Practical Scenario #4: Generating unique primary keys in distributed systems

When multiple services write to the database simultaneously,<span>uuid</span> is a good alternative to <span>auto-incrementing primary keys</span>:

data = {
    "_id": uuid.uuid4().hex,
    "title": "Task A",
}

βœ… No collisions in distributed systemsβœ… Particularly convenient for writing to MongoDB/NoSQL

πŸ”₯ Advanced Usage: Generate a shorter UUID?

Too long? You can:

short_id = uuid.uuid4().hex[:8]  # First 8 characters
print(short_id)  # 'f2c99aab'

Or combine with <span>base64</span> / <span>hashlib</span> for compressed display (can be encrypted)

Summary:<span>uuid</span> can be used like thisπŸ‘‡

Scenario Usage
Unique filename <span>uuid4().hex</span>
User ID <span>uuid4()</span> / <span>uuid5()</span>
Log tracking <span>uuid4()</span>
Database storage <span>uuid4().hex</span>
Temporary Token / Session ID <span>uuid4()</span>

Leave a Comment