Python Redis Lock

4.0.1 · active · verified Sun Apr 12

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.

Warnings

Install

Imports

Quickstart

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.

import redis
import time
import os
from redis_lock import Lock

REDIS_HOST = os.environ.get('REDIS_HOST', 'localhost')
REDIS_PORT = int(os.environ.get('REDIS_PORT', 6379))

# Connect to Redis
client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0)

lock_name = "my-distributed-lock"

# Acquire a lock using a context manager, with a 10-second expiration
# and automatic renewal while the 'with' block is active.
print(f"Attempting to acquire lock '{lock_name}'...")
with Lock(client, lock_name, expire=10, auto_renewal=True, blocking_timeout=5) as lock:
    if lock.acquired:
        print(f"Lock '{lock_name}' acquired! Doing some critical work...")
        # Simulate work that takes longer than the expire time
        # auto_renewal will keep the lock alive.
        time.sleep(15)
        print(f"Work finished. Lock '{lock_name}' will be automatically released.")
    else:
        print(f"Failed to acquire lock '{lock_name}'. Another process holds it.")

# You can also check if a lock is currently held (by anyone)
if Lock(client, lock_name).locked():
    print(f"Lock '{lock_name}' is currently held by someone else (or was not properly released).")
else:
    print(f"Lock '{lock_name}' is not currently held.")

client.close()

view raw JSON →