Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo ID ngẫu nhiên (Random ID) trong Python

Python cung cấp module random và secrets để sinh dữ liệu ngẫu nhiên cho testing, sampling, bảo mật...

Module random cơ bản

import random
print(random.random())  # Float [0.0, 1.0)

Đặc điểm

  • random() là hàm cơ sở, các hàm khác dùng nó
  • Sinh số pseudo-random (giả ngẫu nhiên), deterministic với seed

Sinh số nguyên ngẫu nhiên

from random import randint, randrange

print(randint(0, 20))      # [0, 20] bao gồm cả 2 đầu
print(randrange(0, 20, 2)) # [0, 20) bước 2: 0,2,4...

Chọn ngẫu nhiên từ list

import random

companies = ['RELIANCE', 'TCS', 'INFY', 'SBI', 'PNB', 'HDFC']

# Chọn 1 phần tử
print(random.choice(companies))  # VD: 'INFY'

# Chọn k phần tử KHÔNG trùng lặp (sample)
print(random.sample(companies, 3))  # VD: ['TCS', 'RELIANCE', 'INFY']

# Chọn k phần tử CÓ THỂ trùng lặp (choices)
print(random.choices(companies, k=6))  # VD: ['TCS', 'TCS', 'INFY', ...]

Pseudo-random & Seed

Cùng seed → cùng chuỗi số. Dùng cho reproducible results (testing, debug).

import random

random.seed(10)
for i in range(5): print(random.randint(1, 100))
# 74, 5, 55, 62, 74

random.seed(10)  # Reset seed
for i in range(5): print(random.randint(1, 100))
# 74, 5, 55, 62, 74 (giống hệt)

Số ngẫu nhiên an toàn mật mã (Cryptographically Secure)

Dùng cho password, token, OTP, session ID... Module secrets (Python 3.6+).

Cách 1: secrets.randbelow()

import secrets

for _ in range(10):
    print(10 + secrets.randbelow(500))  # [10, 510)

Cách 2: random.SystemRandom (Python 3.5+)

import random

rng = random.SystemRandom()
for _ in range(10):
    print(10 + rng.randint(0, 499))

Cách 3: secrets.token_bytes / token_hex / token_urlsafe

import secrets

print(secrets.token_bytes(16))    # 16 bytes ngẫu nhiên
print(secrets.token_hex(16))      # 32 ký tự hex
print(secrets.token_urlsafe(16))  # URL-safe base64

Tóm tắt: Khi nào dùng gì?

randomMô phỏng, game, sampling, test data (KHÔNG dùng cho bảo mật)
secrets / SystemRandomPassword, API key, token, OTP, crypto (AN TOÀN cho bảo mật)