Redis in Python

Redis - a fast, open source, in-memory, key-value data store stands for Remote Dictionary Server. It includes various functionalities not limited to cache, database transactions, message broker, and queue. Many cloud platforms like AWS, Azure, GCP, etc offer fully managed Redis services to ease your deployment steps.

This article demonstrates the use of Redis as a key-value store (cache) in python.

  • Make sure to download Redis on your machine.
  • install python Redis client library: pip install redis
  • Run Redis in standalone mode - redis-server --port 6379

Getting started

  • Import redis library and get a connection object/client
import redis

redis_client = redis.Redis(host='localhost', port=6379)
  • Use this client to perform CRUD Operations
  • set takes 3 arguments (key, value, expiry [optional]) and stores the value against key for expiry seconds then pops it.
redis_client.set('ABC', 200, 5)
  • mset accepts dictionary sets multiple key-value pairs.
redis_client.mset({'key1':100,"key2":200})
  • Expiry time for any key can be added or updated using pexpire function
redis_client.pexpire('key1',200)
  • Remove stale or unwanted data from the cache using delete function
redis_client.delete('ABC')

Furthermore, The Redis client library provides connection pooling options where it maintains a pool of reusable connections that can be shared by multiple Redis clients. The pool itself manages the creation and closing of sessions and hence reduces the overhead and minimizes the efforts of these expensive operations.
simply use it while initializing:

import redis
from redis import BlockingConnectionPool

pool = BlockingConnectionPool(max_connections=200,timeout=5)
redis_client = redis.Redis(host='localhost', port=6379, connection_pool=pool)

Note: cmd+click on BlockingConnectionPool to explore more pooling options or visit redis client docs

  • Putting it all together
import redis
from redis import BlockingConnectionPool
from time import sleep

pool = BlockingConnectionPool(max_connections=200,timeout=5)
redis_client = redis.Redis(host='localhost', port=6379, connection_pool=pool)


redis_client.set('ABC', 200, 5)

redis_client.mset({'key1':100,"key2":200,'Car':'Ferrari'})

redis_client.pexpire('key1',7)
print(redis_client.mget(['ABC','Car','key1','key2','Parrot']))

# Waiting for key `ABC` and `key1` to expire
sleep(7)

redis_client.delete('key2')
print(redis_client.get('ABC'))
print(redis_client.mget(['key1','key2']))
  • Output
[b'200', b'Ferrari', b'100', b'200', None]
None
[None, None]

Note: key Parrot didn't exist in the cache, Hence the returned value against it is 'None'

Kartik Kapgate

Kartik Kapgate

Software Engineer | Backend