Search code examples
djangocachingredisdjango-cachedjango-redis

Is there a way to set an expiration time for a Django cache lock?


I have a Django 3.1.3 server that uses Redis for its cache via django-redis 4.12.1. I know that cache locks can generally be set via the following:

with cache.lock('my_cache_lock_key'):
    # Execute some logic here, such as:
    cache.set('some_key', 'Hello world', 3000)

Generally, the cache lock releases when the with block completes execution. However, I have some custom logic in my code that sometimes does not release the cache lock (which is fine for my own reasons).

My question: is there a way to set a timeout value for Django cache locks, much in the same way as you can set timeouts for setting cache values (cache.set('some_key', 'Hello world', 3000))?


Solution

  • I've answered my own question. The following arguments are available for cache.lock():

        def lock(
            self,
            key,
            version=None,
            timeout=None,
            sleep=0.1,
            blocking_timeout=None,
            client=None,
            thread_local=True,
        ):
    

    Cross referencing that with comments from the Python Redis source, which uses the same arguments:

       ``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.
        Note this value can be overridden by passing a ``blocking``
        argument to ``acquire``.
        ``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 integer, both representing the number of seconds to wait.
    

    Therefore, to set the maximum time period of 2 seconds for which a cache lock takes effect, do something like this:

    with cache.lock(key='my_cache_lock_key', timeout=2):
        # Execute some logic here, such as:
        cache.set('some_key', 'Hello world', 3000)