策略一:字符池隨機採樣(均勻分布)
import random
import string
def gen_verification_code_v1(length=6):
"""從 0-9, A-Z, a-z 中隨機選取 length 個字符"""
chars = string.digits + string.ascii_letters # '012...9abc...zABC...Z'
return ''.join(random.sample(chars, length))
# random.sample 無放回採樣,保證字符不重複
# 若允許重複,改用 random.choices(chars, k=length)
策略二:按類別強制包含(數字+大寫+小寫)
def gen_verification_code_v2(length=6):
"""確保至少包含 1 個數字、1 個大寫、1 個小寫,其餘隨機"""
if length < 3:
raise ValueError("Length must be >= 3 to enforce all categories")
# 強制各類一個
parts = [
random.choice(string.digits),
random.choice(string.ascii_uppercase),
random.choice(string.ascii_lowercase)
]
# 剩餘位從全字符池隨機填充
pool = string.digits + string.ascii_letters
parts += random.choices(pool, k=length - 3)
random.shuffle(parts) # 打亂順序
return ''.join(parts)
安全性加強版:secrets 模塊(Python 3.6+)
import secrets
def gen_secure_code(length=6):
"""加密安全的隨機驗證碼,適用於生產環境"""
alphabet = string.digits + string.ascii_letters
return ''.join(secrets.choice(alphabet) for _ in range(length))
# secrets 使用系統 CSPRNG,防預測,適合真實驗證碼、Token、密碼重置
對比總結
| 函數 | 特點 | 適用場景 |
| random.sample | 無重複字符,均勻分布 | 非安全場景、展示用碼 |
| random.choices | 允許重複,均勻分布 | 通用隨機字符串 |
| gen_v2 (分類強制) | 保證字符類型多樣性 | 用戶可讀驗證碼、防 OCR |
| secrets.choice | 加密安全,不可預測 | 生產環境驗證碼、Token、API Key |
示例輸出
v1: gF5UzK
v2: 2Cb1Aa
secure: k9Lm2P