django 文件锁
当我们的需求场景满足:
进程之间的
对同一个文件的排他操作时
我们可以尝试对文件进行加锁。后续扩展锁时,只需要创建锁类,然后在锁管理里面添加即可。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):
"""实现上下文操作""" ... @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__ = """创建锁管理""" 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}")
浙公网安备 33010602011771号