django 文件鎖
當(dāng)我們的需求場景滿足:
進(jìn)程之間的
對同一個文件的排他操作時
我們可以嘗試對文件進(jìn)行加鎖。后續(xù)擴(kuò)展鎖時,只需要創(chuàng)建鎖類,然后在鎖管理里面添加即可。import fcntl
import os from abc import ABCMeta, abstractmethod class Lock(metaclass=ABCMeta): __doc__ = """抽象鎖雞肋, 用于定義鎖""" @abstractmethod def acquire(self): """獲取鎖""" ... @abstractmethod def release(slef): """釋放鎖""" ...
@abstractmethod def __enter__(self):
"""實(shí)現(xiàn)上下文操作""" ... @abstractmethod def __exit__(self, exc_type, exc_value, traceback): ... class FileLock(Lock): __doc__ = """文件鎖""" def init (self, lockfile_path): self.lockfile_path = lockfile_path self.file = None def acquire(self): lock_dir = os.path.dirname(self.lockfile_path) if lock_dir: os.makedirs(lock_dir, exist_ok=True) self. file = open(self.lockfile path, try: fcntl.flock(self, file, fcntl.LOCK_Ex | fcntl.LOCK_NB) except BlockingIoError: raise RuntimeError(f"Lock is already held for: {self,lockfile path}") def __enter__(self): self.acquire() return self def __exit__(self,exc_type,exc_value,traceback): self.release() class LockManager(object): __doc__ = """創(chuàng)建鎖管理""" def __init__(self,lock_type='file', **kwa): self.lock_type=lock_type self.kwa = kwa def create_lock(self): if self.lock_type == 'file': return Filelock(**self.kwa) raise ValueError(f"不支持的鎖類型:{self.lock_type}")
浙公網(wǎng)安備 33010602011771號