pythonredistransactionsredis-py

What are equivalent functions of MULTI and EXEC commands in redis-py?


I tested all the transaction commands (MULTI, EXEC, WATCH, DISCARD) in redis-cli. But when i tried with redis-py the following error occurred:

AttributeError: 'Redis' object has no attribute 'multi'

I have tried the following code snippet:

import redis,time

r = redis.Redis()
try:
    r.set("transError",10)
    r.watch("transError")
    var = r.get("transError")
    var = int(var) + 1
    print "Run other client to simulate an error without transaction"
    time.sleep(4)
    r.multi()
    r.set("transError",var)
    r.execute()
    print "Value in first client",r.get("transError")

except redis.WatchError:
    print "Value Altered"

I have seen code example that is using multi() and execute() but they are not working for me. Any help?


Solution

  • In redis-py MULTI and EXEC can only be used through a Pipeline object.

    Try the following:

    r = redis.Redis()
    p = r.pipeline()
    p.set("transError", var)
    p.execute()
    

    With the monitor command through the redis-cli you can see MULTI, SET, EXEC sent when p.execute() is called. To omit the MULTI/EXEC pair, use r.pipeline(transaction=False).