Locks

class Lock(client: Redis | RedisCluster, name: StringT, timeout: float | None = None, sleep: float = 0.1, blocking: bool = True, blocking_timeout: float | None = None)[source]

A shared, distributed Lock inspired by the Distributed locks documentation and the Redlock Algorithm

The lock can be used with both Redis and RedisCluster either explicitly or as an async context manager:

import asyncio
import coredis
from coredis.exceptions import LockError
from coredis.patterns.lock import Lock
client = coredis.Redis()
async with client:
    async with Lock(client, "mylock", timeout=1.0):
        # do stuff
        await asyncio.sleep(0.5)
        # lock is implictly released when the context manager exits
    try:
        async with Lock(client, "mylock", timeout=1.0):
            # do stuff that takes too long
            await asyncio.sleep(1)
            # lock will raise upon exiting the context manager
    except LockError as err:
        # roll back stuff
        print(f"Expected error: {err}")
Parameters:
  • timeout – indicates a maximum life for the lock. By default, it will remain locked until release() is called. timeout can be specified as a float or integer, both representing the number of seconds to wait.

  • sleep – indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.

  • blocking – indicates whether calling acquire() should block until the lock has been acquired or to fail immediately, causing acquire() to return False and the lock not being acquired. Defaults to True.

  • blocking_timeout – indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of None indicates continue trying forever. blocking_timeout can be specified as a float or int, both representing the number of seconds to wait.

async acquire() bool[source]

Use SET with the NX option to acquire a lock. If the lock is being used with a cluster client the ensure_replication() context manager will be used to ensure that the command was replicated to atleast half the replicas of the shard where the lock would be acquired.

Raises:

LockError

async release() None[source]

Releases the already acquired lock

Raises:

LockReleaseError

async extend(additional_time: float) bool[source]

Adds more time to an already acquired lock.

Parameters:

additional_time – can be specified as an integer or a float, both representing the number of seconds to add.

Raises:

LockExtensionError

property replication_factor: int

Number of replicas the lock needs to replicate to, to be considered acquired.