-
Notifications
You must be signed in to change notification settings - Fork 117
Add context manager support #25
Comments
The thing is the lock is not acquired when instantiating Redlock but when calling The code could be changed to with dlm.lock("my_resource_name",1000) as lock:
pass but we would still need to handle the case where the lock failed. Then an exception needs to be raised and this is something that is not done in the original code. |
I mean, a To me mirroring the standard |
You may try this piece of code: class RedisDistributedLock:
def __init__(self, redis_lock: Redlock, lock_key: str, ttl: int = 30):
"""
A context based redis distributed lock
:param redis_lock: Redlock object
:param lock_key: the resource key to lock
:param ttl: timout after ttl seconds
"""
self._rlk = redis_lock
self._key = lock_key
self._ttl = ttl
self._lock = None
def __enter__(self):
self._lock = self._rlk.lock(self._key, self._ttl)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._rlk.unlock(self._lock) And here's an example: with RedisDistributedLock(Redlock(<connection info>),<key>,<ttl>) as rdl:
# do something |
redlock-py looks like a nice project, but the last commit was on March 8, 2016. It doesn’t look like redlock-py is maintained. Consider using Pottery’s implementation of Redlock instead (I develop/maintain Pottery). Pottery’s Redlock has a couple of nice features over redlock-py:
|
It would be nice to use it as context manager. Like the following:
The text was updated successfully, but these errors were encountered: