Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 610
Ahsanul Haque Avatar asked Aug 02 '15 06:08

Ahsanul Haque


People also ask

What is multi in Redis?

The multi command tells Redis to begin a transaction block. Any subsequent commands will be queued up until you run an exec command, which will execute them. The following commands form a single transaction block.

How do I use Redis commands?

To start Redis client, open the terminal and type the command redis-cli. This will connect to your local server and now you can run any command. In the above example, we connect to Redis server running on the local machine and execute a command PING, that checks whether the server is running or not.


1 Answers

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).

like image 52
ntki Avatar answered Sep 19 '22 19:09

ntki