random.random(), random.randint(a, b), random.choice(seq), random.shuffle(list), random.sample(seq, k). 게임, 시뮬레이션, 데이터에서 샘플 뽑기에 충분. random.seed(42) 로 재현 가능 테스트용 seedable. 암호학적으로 안전 X — 토큰, 비밀번호, 공격자가 예측 못 해야 할 거에 사용 X.
secrets — 보안 민감 랜덤성
secrets.token_hex(16), secrets.token_urlsafe(32), secrets.choice(seq). random 과 같은 모양, OS 의 cryptographic RNG 사용. 세션 토큰, 비밀번호 reset 코드, 추측 가능성 중요한 모든 거에 사용.
hashlib — 컨텐츠 해싱
SHA-256 이 디폴트 일상 해시. hashlib.sha256(b"data").hexdigest(). 다른 알고리즘 있지만 필요 없으면 SHA-256. md5 와 sha1 여전히 작동하지만 collision-resistant X — 보안 경계엔 사용 X. 항상 bytes 해시, 문자열 X — 먼저 인코드.
uuid — 유니크 식별자
uuid.uuid4() 가 랜덤 UUID (가장 흔한 케이스). uuid.uuid1() 이 MAC + 시간 사용 (둘 다 leak). 디폴트로 uuid4 계속 사용, 다른 거 특정 use case. 표준 hyphen 문자열 형태엔 str(uuid.uuid4()).
import secrets
# 토큰 생성
print(secrets.token_hex(16)) # 32-글자 hex (16 바이트)
print(secrets.token_urlsafe(32)) # URL-safe base64
print(secrets.token_bytes(8)) # 8 랜덤 바이트
# 랜덤 선택 (cryptographically)
print(secrets.choice(["a", "b", "c"]))
# 비교 — 같은 모양에 random vs secrets
import random
print("random:", random.randint(1, 100)) # seed 알면 예측 가능
print("secrets:", secrets.randbelow(100)) # 예측 불가
# secrets 사용처 — 세션 토큰, 비밀번호 reset, API 키.
# random 사용처 — 테스트 데이터 셔플, 샘플 뽑기, 시뮬레이션.
hashlib — 컨텐츠 해싱·python
import hashlib
# SHA-256 이 일상 디폴트
data = b"hello world"
h = hashlib.sha256(data)
print(h.hexdigest()) # 'b94d27b9934d3e08a52e52d7da7dab...'
print(h.digest()) # raw bytes
# chunk 로 파일 해싱 (큰 파일 streaming)
import pathlib
p = pathlib.Path("/etc/hostname")
h = hashlib.sha256()
with p.open("rb") as f:
while chunk := f.read(8192):
h.update(chunk)
print(h.hexdigest())
# 문자열 해싱 — bytes 로 인코드 먼저
h = hashlib.sha256("안녕".encode("utf-8")).hexdigest()
print(h)
uuid — 유니크 식별자·python
import uuid
# uuid4 — 랜덤, 일상 선택
print(uuid.uuid4()) # ad8a0a2c-...
print(str(uuid.uuid4())) # 표준 hyphen 문자열
# uuid1 — MAC + 시간 기반 (둘 다 leak — 보통 안 원함)
# uuid3, uuid5 — namespaced (같은 이름이면 deterministic)
# 흔한 사용 — 데이터베이스 랜덤 ID
records = [{"id": str(uuid.uuid4()), "data": x} for x in ["a", "b", "c"]]
for r in records:
print(r)
shutil — 고레벨 파일 연산·python
import shutil
import tempfile
from pathlib import Path
# 복사
src = Path("/etc/hostname")
dst = Path("/tmp/hostname-copy")
shutil.copy(src, dst)
print(dst.read_text(encoding="utf-8"))
dst.unlink()
# 이동 (rename)
f = Path("/tmp/source.txt")
f.write_text("hi", encoding="utf-8")
shutil.move(str(f), "/tmp/dest.txt")
Path("/tmp/dest.txt").unlink()
# 디렉토리 트리 제거 (재귀)
with tempfile.TemporaryDirectory() as td:
sub = Path(td) / "nested" / "deeper"
sub.mkdir(parents=True)
(sub / "file.txt").write_text("hi", encoding="utf-8")
# shutil.rmtree(td) — 어쨌든 컨텍스트 종료 시 일어남
# 터미널 크기, 빈 디스크 공간
print(shutil.get_terminal_size())
print(shutil.disk_usage("/"))
(a) secrets.token_urlsafe(24) 로 세 세션 토큰 생성 + 출력. (b) 문자열 "피파, 안녕" 을 SHA-256 으로 해싱 (UTF-8 인코드 먼저) + hex digest 출력. (c) 랜덤 UUID4 생성 + tempfile 의 temp 파일 이름 suffix 로 사용. (d) shutil.disk_usage('/') 로 사람 읽기 좋게 (GB) 빈 공간 출력.
Progress
Progress is local-only — sign in to sync across devices.