diff --git a/changelog.d/752.bugfix b/changelog.d/752.bugfix new file mode 100644 index 00000000..68c94278 --- /dev/null +++ b/changelog.d/752.bugfix @@ -0,0 +1 @@ +Added blocking parameter for `cache.lock` \ No newline at end of file diff --git a/django_redis/client/default.py b/django_redis/client/default.py index 3219f7c9..940e1a0e 100644 --- a/django_redis/client/default.py +++ b/django_redis/client/default.py @@ -326,9 +326,7 @@ def expire( key = self.make_key(key, version=version) - # for some strange reason mypy complains, - # saying that timeout type is float | timedelta - return client.expire(key, timeout) # type: ignore + return client.expire(key, timeout) def pexpire( self, @@ -345,11 +343,7 @@ def pexpire( key = self.make_key(key, version=version) - # Temporary casting until https://github.com/redis/redis-py/issues/1664 - # is fixed. - # for some strange reason mypy complains, - # saying that timeout type is float | timedelta - return bool(client.pexpire(key, timeout)) # type: ignore + return bool(client.pexpire(key, timeout)) def pexpire_at( self, @@ -393,6 +387,7 @@ def lock( version: Optional[int] = None, timeout: Optional[float] = None, sleep: float = 0.1, + blocking: bool = True, blocking_timeout: Optional[float] = None, client: Optional[Redis] = None, thread_local: bool = True, @@ -405,6 +400,7 @@ def lock( key, timeout=timeout, sleep=sleep, + blocking=blocking, blocking_timeout=blocking_timeout, thread_local=thread_local, ) diff --git a/django_redis/client/herd.py b/django_redis/client/herd.py index 94d539cd..c5c6d7d8 100644 --- a/django_redis/client/herd.py +++ b/django_redis/client/herd.py @@ -26,9 +26,7 @@ def _is_expired(x, herd_timeout: int) -> bool: return True val = x + random.randint(1, herd_timeout) - if val >= herd_timeout: - return True - return False + return val >= herd_timeout class HerdClient(DefaultClient): diff --git a/tests/test_backend.py b/tests/test_backend.py index 8619931e..e5c54e18 100644 --- a/tests/test_backend.py +++ b/tests/test_backend.py @@ -677,7 +677,19 @@ def test_expire_at(self, cache: RedisCache): def test_lock(self, cache: RedisCache): lock = cache.lock("foobar") - lock.acquire(blocking=True) + assert lock.acquire(blocking=True) + + assert cache.has_key("foobar") + lock.release() + assert not cache.has_key("foobar") + + def test_lock_not_blocking(self, cache: RedisCache): + lock = cache.lock("foobar") + assert lock.acquire(blocking=False) + + lock2 = cache.lock("foobar") + + assert not lock2.acquire(blocking=False) assert cache.has_key("foobar") lock.release() @@ -685,7 +697,7 @@ def test_lock(self, cache: RedisCache): def test_lock_released_by_thread(self, cache: RedisCache): lock = cache.lock("foobar", thread_local=False) - lock.acquire(blocking=True) + assert lock.acquire(blocking=True) def release_lock(lock_): lock_.release()