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
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.
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
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 Instance in python
Redis package has a Redis Class that needs to be instantiated to connect to the Redis Server operating on our machine.
REDIS_PORT = 6379
REDIS_HOST = '127.0.0.1'
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)
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.
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.