How To Use Redis with Python

Share this blog with others!

In the previous blogs about Redis, we learned the basics of Redis, Commands, and Hash Data Structure in Redis. This Time we will learn How to use Redis With Python?

Prerequisite for Using Redis with Python

Make Sure that Redis is installed on your machine. If working on Windows read How to install Redis on Windows 10?

Installing Redis in Python

We have our Redis set up in our machine now we want a package that would help us to connect with the Redis Server on our machine with the help of the python program.

Redis can be installed in python using pip (package installer python).

$ pip install redis

Bash/Shell

This command will install the Redis Python Package which will help us to connect with the Redis Server on our machine and execute in-memory No-SQL database commands.

Use Redis in Python

Now, when we have installed the Redis Python Package. It’s time to use it.

Import Redis

As you would already know, installed packages in python are imported to make use of it. So Let’s import Redis in Python.

>>> import redis

Python

Package installed successfully if no error occurs.

Run Redis Server

The Redis Python package makes use of the Redis server on our machine, So before running a python program that includes Redis commands, run the server, else you will get an error.

$ redis-server

Bash/Shell

Redis Instance in python

Redis package has a Redis Class that needs to be instantiated to connect to the Redis Server operating on our machine.

import redis

REDIS_PORT = 6379
REDIS_HOST = '127.0.0.1'

r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)

Python

By Default, the Redis Server operates on the localhost and the port 6379. You can change it at the time of installation.

The Redis Class in the Redis package takes the Host and the Port name and sets up a connection with our Redis Server on our Localhost.

Redis Commands in Python

Now it’s time to execute some of the Redis commands in Python to test whether the connection with Redis Server is built or not.

print(r.ping())
print(r.keys())
r.set('key1', 'value1')
print(r.get('key1'))
r.set('key2', 'value2')
print(r.keys())

Python

True
[]
b'value1'
[b'key2', b'key1']

Python

The Ping Command in Redis Python gives boolean Value i.e True (If the Connection with the Redis Server is proper).

Learn more about how to work with Redis in Python form the official Redis-py Documentation.

0 0 votes
Article Rating

Share this blog with others!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top