[Solved]-Using a Lock with redis-py

14👍

There are two problems:

  1. As others have said, you need to use two different keys for the lock and the hash.
  2. The syntax is wrong.

To elaborate on point 2, here are the steps involved with using a lock:

  1. Create a Lock object.
  2. Acquire the lock.
  3. Do critical stuff.
  4. Release the lock.

Without using a context manager (the with ... statement), the code might look like this:

lock = r.lock('my_lock')
lock.acquire(blocking=True)
r.set('foo', 'bar')
lock.release()

With a context manager, that code gets simplified to this:

with r.lock('my_lock'):
    r.set('foo', 'bar')

What is happening here is the following:

  1. r.lock() creates and returns a Lock object.
  2. Lock.__enter__() is called automatically, which in turn calls Lock.acquire().
  3. The indented code executes.
  4. Lock.__exit__() is called automatically, which in turn calls Lock.release().

You can see this in the redis-py source code.

4👍

You are trying to set a dictionary in the same key as the lock. You want to have a key for the lock and another for the dictionary.

Leave a comment