python-redis-lock is a Python library that provides a distributed lock context manager, implemented using Redis's `SETNX` (SET if Not eXists) and `BLPOP` operations. It aims to offer an interface similar to Python's built-in `threading.Lock`. The current version is 4.0.1, and it maintains an active release cadence, with its latest major update in late 2022.
pip install python-redis-lockVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to acquire and use a distributed lock with `python-redis-lock` using a context manager. It highlights setting an expiration (`expire`) and enabling automatic renewal (`auto_renewal`) to prevent locks from being held indefinitely if the application crashes. It also shows checking the lock status.
Upgrade to Python 3.7+ or pin `python-redis-lock` to a version prior to 4.0.0.
Always use the `auto_renewal=True` parameter in conjunction with `expire` when creating a `Lock` instance. This ensures the lock is automatically renewed as long as the Python process is running within the `with` block, and will expire cleanly if the process terminates unexpectedly. Example: `Lock(client, 'my-lock', expire=60, auto_renewal=True)`.
Review your code and remove any usage of `lock.release(force=True)`. Ensure proper lock acquisition and release logic without relying on force-releasing locks, which can lead to race conditions.
Understand that this library is suitable for single-instance Redis distributed locking. If your application requires the guarantees of the Redlock algorithm (e.g., across multiple Redis masters), you will need to use a different library (e.g., `redlock-py`) or implement Redlock logic yourself. Do not confuse `redis_lock.Lock` with `redis.lock.Lock` (from `redis-py`), as they are separate implementations.
Install the library using pip: `pip install python-redis-lock`
Ensure your Redis server is running and accessible. Verify the host and port in your Redis client instantiation, e.g., `client = redis.StrictRedis(host='localhost', port=6379)`.
Increase the `timeout` parameter when creating the `Lock` object or when calling `acquire()`, or investigate the process holding the lock to ensure it's released promptly. Example: `lock = redis_lock.Lock(client, 'my-lock', expire=10, timeout=5)`.
Replace the `blocking` argument with `timeout`. For a non-blocking attempt, use `lock.acquire(timeout=0)`. For a blocking attempt, either omit `timeout` or set it to a desired wait duration. Example: `lock.acquire(timeout=5)`.