Using Redis Server In Python


In this article, we will see how we can use the Redis server using Python.

Redis server is a kind of storage, which stores values in key, value format. It can be used as a messenger, database, temporary storage, etc.


  • Redis server must be installed on your pc

In the windows terminal, open Ubuntu mode and run command “redis-server” to start the server

Create folder and create a file with (I choose Run below command in terminal to create a virtual environment 

“pipenv shell”

After this install Redis by executing below command,

“pipenv install redis”

Below is the code to initialize the Redis server which provides the interface to all Redis commands

import redis
_redis = redis.Redis(host='localhost', port=6379)

We passed host as localhost as we are running Redis on the local server and by default Redis will be listening at 6379 port

Now we will see,

  • set value in the key value mechanism 
  • get the value from Redis buffer
  • delete the value from Redis buffer
import redis

_redis = redis.Redis(host='localhost', port=6379)

#set value in the key value mechanism  
_redis.set("TestA", "testA")

#get the value from redis buffer
print("TestA:", _redis.get("TestA"))

#delete the value from buffer
print("TestA", _redis.get("TestA"))

Below is the output snap of the code, we can see the stored value and we retrieve and deleted the value as well

Below is the code to store the object in Redis and retrieve it.

import redis
import json

_redis = redis.Redis(host='localhost', port=6379)

class Person():

p = Person()
p.Name = "OK"
p.age = 10
p.Bloodgroup = "A+"

_redis.set("TestB", json.dumps(p.__dict__))


In this article, we saw the usage of Redis server in python. For reference, I attached the project to this article. You can download and run the below command from the project directory to execute the code 

“pipenv shell”
“pipenv install redis”

Run the file.