How to Generate a UUID in Python
Python uuid Standard Library Overview
Python has built-in the uuid module since version 2.5, requiring no additional packages. The module implements UUID versions 1, 3, 4, and 5 as defined in RFC 4122, providing the UUID class and several convenient generation functions. UUID objects can not only be converted to strings but also access individual fields (time_low, time_mid, clock_seq, etc.) and multiple representations like bytes, int, and hex. This makes Python's UUID operations very flexible, suitable for scenarios requiring precise control over UUID format.
Code Examples for Generating Each UUID Version
import uuid
# UUID v4๏ผๆๅธธ็จ๏ผ้ๆบ็ๆ๏ผ
id_v4 = uuid.uuid4()
print(id_v4) # UUID ๅฏน่ฑก
print(str(id_v4)) # ๅญ็ฌฆไธฒ่กจ็คบ
print(id_v4.hex) # ๆ ่ฟๅญ็ฌฆ
print(id_v4.bytes) # 16 ๅญ่
print(id_v4.int) # ๆดๆฐ
# UUID v1๏ผๆถ้ดๆณ + MAC ๅฐๅ๏ผ
id_v1 = uuid.uuid1()
print(id_v1)
print(id_v1.time) # ๆถ้ดๆณๅญๆฎต
print(id_v1.node) # ่็น๏ผMAC๏ผๅญๆฎต
# UUID v3๏ผMD5 ๅๅธ๏ผ็กฎๅฎๆง๏ผ
id_v3 = uuid.uuid3(uuid.NAMESPACE_URL, 'https://example.com')
print(id_v3)
# UUID v5๏ผSHA-1 ๅๅธ๏ผ็กฎๅฎๆง๏ผ
id_v5 = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')
print(id_v5)
# ๆ ๅๅฝๅ็ฉบ้ด
print(uuid.NAMESPACE_DNS) # 6ba7b810-9dad-11d1-80b4-00c04fd430c8
print(uuid.NAMESPACE_URL) # 6ba7b811-9dad-11d1-80b4-00c04fd430c8
print(uuid.NAMESPACE_OID) # 6ba7b812-9dad-11d1-80b4-00c04fd430c8
print(uuid.NAMESPACE_X500) # 6ba7b814-9dad-11d1-80b4-00c04fd430c8
Formatting UUID Output
import uuid
uid = uuid.uuid4()
# ไธๅๆ ผๅผ่พๅบ
print(str(uid)) # ๆ ๅๆ ผๅผ๏ผxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
print(uid.hex) # ๆ ่ฟๅญ็ฌฆ๏ผxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
print(str(uid).upper()) # ๅคงๅๆ ผๅผ
print(str(uid).replace('-', '')) # ็งป้ค่ฟๅญ็ฌฆ
# ่งฃๆ UUID ๅญ็ฌฆไธฒ
parsed = uuid.UUID('550e8400-e29b-41d4-a716-446655440000')
parsed_no_dash = uuid.UUID('550e8400e29b41d4a716446655440000') # ๆ ่ฟๅญ็ฌฆไนๅฏไปฅ
parsed_braces = uuid.UUID('{550e8400-e29b-41d4-a716-446655440000}') # ่ฑๆฌๅท
# ๆฅ็็ๆฌๅๅไฝ
print(parsed.version) # 4
print(parsed.variant) # UUID ๅไฝๆ ่ฏ
# ๆน้็ๆ
uuids = [str(uuid.uuid4()) for _ in range(10)]
Using UUID Primary Keys in Django
Django natively supports UUID as model primary keys using models.UUIDField. This is the recommended approach in Django for avoiding auto-increment primary keys and improving security. UUID primary keys do not expose the total count and order of database records, making them suitable for resource IDs in public-facing APIs.
# Django ๆจกๅ็คบไพ
import uuid
from django.db import models
class Article(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4, # ๆณจๆ๏ผไผ ๅฝๆฐๅผ็จ่้่ฐ็จ็ปๆ
editable=False
)
title = models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at']
# ไฝฟ็จ
article = Article(title='Hello World')
article.save()
print(article.id) # UUID ๅฏน่ฑก
print(str(article.id)) # ๅญ็ฌฆไธฒ
Using UUID with SQLAlchemy
# SQLAlchemy ็คบไพ
import uuid
from sqlalchemy import Column, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = 'users'
# PostgreSQL ๅ็ UUID ็ฑปๅ
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
# ๆไฝฟ็จ String ๅ
ผๅฎนๆๆๆฐๆฎๅบ
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
UUID Type Annotations in FastAPI
# FastAPI + Pydantic ็คบไพ
from uuid import UUID, uuid4
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
id: UUID = None
name: str
def __init__(self, **data):
if 'id' not in data:
data['id'] = uuid4()
super().__init__(**data)
@app.get('/items/{item_id}')
async def get_item(item_id: UUID):
# FastAPI ่ชๅจ้ช่ฏ item_id ๆฏๅฆๆฏๅๆณ UUID
return {'id': str(item_id)}
@app.post('/items')
async def create_item(item: Item):
return item
Validating UUID Strings
import uuid
def is_valid_uuid(uuid_string: str) -> bool:
"""้ช่ฏๅญ็ฌฆไธฒๆฏๅฆๆฏๅๆณ็ UUID"""
try:
uuid.UUID(uuid_string)
return True
except ValueError:
return False
def is_valid_uuid_v4(uuid_string: str) -> bool:
"""้ช่ฏๅญ็ฌฆไธฒๆฏๅฆๆฏๅๆณ็ UUID v4"""
try:
u = uuid.UUID(uuid_string)
return u.version == 4
except ValueError:
return False
# ๆต่ฏ
print(is_valid_uuid('550e8400-e29b-41d4-a716-446655440000')) # True
print(is_valid_uuid('not-a-uuid')) # False
print(is_valid_uuid_v4('550e8400-e29b-41d4-a716-446655440000')) # False (v1)
print(is_valid_uuid_v4(str(uuid.uuid4()))) # True
Try the free tool now
Use Free Tool โ