[Django]-How to lock access to django redis cache

-7👍

As mentioned in the comments, easy way is to define a key in redis cache and try to delete cache before accessing desired key.

while cache.delete('tmp_key') == 0:
    continue
# do something with your desired key
cache.set('tmp_key', 'unlocked', timeout=None)

4👍

Django redis offers a locking mechanism you can use without running into a race condition. My settings.py file uses the same CACHES settings as specified by the documentation linked to above.

The following code shows the lock in the console:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'filestorage.settings')
from django.core.cache import caches
caches['default']
<django_redis.cache.RedisCache object at 0x7fbc817e03c8>
caches['default'].lock('la')
<redis.lock.LuaLock object at 0x7fbc80e772e8>

The lock can be used in a manner similar to Python’s threading.Lock:

l = caches['default'].lock('la')
l
<redis.lock.LuaLock object at 0x7fbc80e77320>
l.acquire()
True
l.release()

Leave a comment