Redis with Python
In this article, we are going to look into how we can interact with Redis using python.
Prerequisite:
Redis server should be installed and running. If you have not already installed then, you can refer to the given below medium article that explains how to install and run Redis in Linux-based machines.
https://medium.com/@amar1611/getting-started-with-redis-a3bec0877c58
Getting Started with Python:
For interacting with Redis we need to install the Redis python package using the following command:
$ pip install redisFirstly we need to create a connection to the Redis server.
import redis
redis_conn = redis.Redis(host='localhost', port=6379)Verify if we are connected to the Redis server or not. It should return True if we are connected.
redis_conn.ping()Using the set funtion, we can save key-value pairs
redis_conn.set('sum', 1000)
redis_conn.set('mean', 100)Using the get function, we can get the value for saved keys
print(redis_conn.get('sum'))
print(redis_conn.get('mean'))We can also save multiple key-value pairs using the mset function
redis_conn.mset({'std': 20,'variance':5})
print(redis_conn.get('std'))
print(redis_conn.get('variance'))To get the list of all the keys we can use the keys function
redis_conn.keys()To check if a key exists in the cache or not we can use exists function. In real-world scenarios, we first check if the key exists in the cache. If true then we fetch the data from the cache else we fetch the data from the database and store it in the cache. Here is the python code for the same
if redis_conn.exists('mean'):
print("Getting data from Redis Cache")
mean = redis_conn.get('mean')
else:
print("Getting data from datbase")
# Get the data from the database
# For demo we will just assign it a value
mean = 100
redis_conn.set('mean', mean)We can also set the time duration after which a key will be deleted from the cache using the psetex function. It takes three parameters namely name, time_ms, and value.
Get Amar Nath’s stories in your inbox
Join Medium for free to get updates from this writer.
In the below given example, the key(mode) gets deleted after 1 second. And if we try to fetch the value after 1 second we will get None as output.
import time# Set the value(150) for key(mode) that will expire in 1000 miliseconds
redis_conn.psetex('mode', 1000, 150)# Get the value of mode from cache
print(redis_conn.get('mode')) # Output: b'150'# Sleep for 2 seconds
time.sleep(2)# Get the value of mode from cache
print(redis_conn.get('mode')) # Output: None
Hope this article would have given you a brief idea about how we can interact with Redis using Python.
References:








