Skip to content

Instantly share code, notes, and snippets.

@seckcoder
Last active December 18, 2015 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seckcoder/5697196 to your computer and use it in GitHub Desktop.
Save seckcoder/5697196 to your computer and use it in GitHub Desktop.
redis transaction
import redis
client = redis.StrictRedis()
client.flushdb()
def incr(pipe):
value = pipe.get('key')
value = int(value) + 1
pipe.multi()
pipe.set('key', value)
def aincr(pipe):
value = pipe.get('key')
value = int(value) + 1
pipe.multi()
pipe.set('akey', value)
def randmove(pipe):
"""randomly move a member between redis set"""
value = pipe.srandmember("skey")
pipe.multi()
pipe.sadd("askey", value)
pipe.srem("skey", value)
def randmove_wrongway(pipe):
value = pipe.spop("skey") # error! as we are watching skey, we can't modify it.
pipe.multi()
pipe.sadd("askey", value)
client.set("key", 2)
client.transaction(aincr, "key")
print client.get("akey"), client.get("key")
client.sadd("skey", 2, 3, 4)
client.transaction(randmove, "skey")
print client.smembers("skey"), client.smembers("askey")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment