jisubae
initial commit
5e8f045
raw
history blame
1.69 kB
"""
μœ ν‹Έλ¦¬ν‹° ν•¨μˆ˜ λͺ¨λ“ˆ
κ³΅ν†΅μœΌλ‘œ μ‚¬μš©λ˜λŠ” μœ ν‹Έλ¦¬ν‹° ν•¨μˆ˜λ“€μ„ λͺ¨μ•„놓은 λͺ¨λ“ˆμž…λ‹ˆλ‹€.
"""
import os
import fcntl
import pytz
from contextlib import contextmanager
from datetime import datetime
# ν•œκ΅­ μ‹œκ°„λŒ€ μ„€μ •
KOREA_TZ = pytz.timezone('Asia/Seoul')
def get_korea_datetime_now():
"""ν•œκ΅­ μ‹œκ°„λŒ€μ˜ ν˜„μž¬ μ‹œκ°„μ„ λ°˜ν™˜"""
return datetime.now(KOREA_TZ)
def get_current_datetime_str(dt=None):
"""ν•œκ΅­ μ‹œκ°„λŒ€μ˜ μ‹œκ°„μ„ λ¬Έμžμ—΄λ‘œ 포맷"""
if dt is None:
dt = get_korea_datetime_now()
return dt.strftime('%Y-%m-%d %H:%M:%S')
def get_current_date_str():
"""ν˜„μž¬ λ‚ μ§œλ₯Ό ν•œκ΅­ μ‹œκ°„μœΌλ‘œ λ°˜ν™˜"""
return get_korea_datetime_now().strftime("%Y-%m-%d")
@contextmanager
def file_lock(lock_file_path):
"""
파일 기반 배타적 μž κΈˆμ„ μ œκ³΅ν•˜λŠ” context manager
Args:
lock_file_path: 잠금 파일 경둜
Yields:
None (λ§₯락 κ΄€λ¦¬μžλ‘œλ§Œ μ‚¬μš©)
Examples:
>>> with file_lock('/tmp/test.lock'):
... # 잠금이 κ±Έλ¦° μƒνƒœμ—μ„œ μž‘μ—… μˆ˜ν–‰
... pass
"""
# 잠금 파일이 μ—†μœΌλ©΄ 생성
if not os.path.exists(lock_file_path):
open(lock_file_path, 'w').close()
# 잠금 νŒŒμΌμ„ μ—΄κ³  배타적 잠금 νšλ“
with open(lock_file_path, 'r') as lock_file:
try:
# 배타적 잠금 μ‹œλ„ (λ‹€λ₯Έ ν”„λ‘œμ„ΈμŠ€κ°€ λŒ€κΈ°)
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
# 잠금 νšλ“ 성곡, μž‘μ—… μˆ˜ν–‰
yield
finally:
# 잠금 ν•΄μ œ
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)