Snippets python / redis

Redis Python

By Marcelo Fernandes Aug 12, 2017

Installation

sudo pip install redis

Run redis server


# move to your redis main folder and type:
./src/redis-server

# if you want to use the redis console, in a new terminal type:
./src/redis-cli

Open a Python connection to Redis


import redis

r = redis.Redis(host='127.0.0.1',
                port=6379)

Common usage


# ex stands for expiration, in seconds.
r.set(name='car:color', value='blue', ex=500)

r.get('car:color')
# b'blue'

# living time
r.ttl('car:color')
# 421

r.delete('car:color')

r.exists('car:color')
# False

Pipelines

Pipelines are a subclass of the base Redis class that provide support for buffering multiple commands to the server in a single request. They can be used to dramatically increase the performance of groups of commands by reducing the number of back-and-forth TCP packets between the client and server.

The commands from the pipeline are executed atomically as a group. Still, we can get rid of that setting the pipeline attribute transaction to False if wanted (not the case)


r.set('bing', 'bang')
r.set('ping', 'pong')
r.set('buzz', 'fizz')

pipe = r.pipeline()
# pipe = r.pipeline(transaction=False)

pipe.set('foo', 'bar')
pipe.get('bing')
pipe.get('ping')

pipe.execute()
# [True, b'bang', b'pong']


Notes


References: