Interacting with Redis using Python
Darryl is a software developer at Bandwidth, working on the core voice systems that power our global enterprise communications platform. Check out our open positions if you’d like to work with Darryl and the team. Join the BAND!
Like Python? Like Redis? Like Both? Don’t like either but want an easy coding project to do that will make you feel like a boss afterwards?
If you answered yes, or no, to any of the previous questions then you should read this article and code along!
The goal will be to write a small program that can connect to a live Redis database, execute a command within Redis, and see the results.
To keep this as lightweight as possible, there won’t be too many details on how to properly get Redis set up or the setup or inner workings of Docker. The plan is to get Redis set up ASAP, and to go right into running Python commands.
This guide will use three things:
- Python 3.10.0 (Should be good as long as it’s Python 3)
- Redis 6.2.6 (Most versions should work)
- Docker 20.10.7 (Most recent versions should work)
*Note: The code can be done without using Docker as well. A link will be provided in the Redis setup section of this document.
**Note: This is written from a Mac computer’s implementation. Linux users may be able to follow the guide without much issue, but Windows users will have to do different steps for the setup. I’ll include some links in the setup for Windows users and hopefully that will get you going in the right direction.
Intro to Tech Stack
Python: One of the most popular programming languages in the world and while easy for beginners to get started with, can be used to build powerful applications.
Redis: An awesome key value store often used as a cache (place to get data quickly) solution for system architectures.
Docker: a way to “containerize” applications. Essentially, it’s used to package up an application and have it run on a bunch of different computers of different types and operating systems.
The first step is to set up Redis. There are many ways to do this for most platforms here https://redis.io/docs/getting-started/.
Ultimately, how Redis is run isn’t as important as having a running Redis to run commands against. So, feel free to use whatever method for installing Redis that is most comfortable.
Here’s a link to install Docker: https://docs.docker.com/get-docker/
We will download Redis in a Docker container with the command:
docker pull redis
and, after the download is finished, run the following command to start Redis inside the container:
docker run -p 6378:6379 -d redis
This will download the Redis container. The
-p 6378:6379 maps our computer’s local 6378 port to the 6379 port of the container (6379 is the default port for Redis). This lets us interact with the Redis container as if we were running Redis directly on our machine. The -d runs our container in detached mode, which keeps our terminal free for more commands.
Now we should be ready to start coding!
To check everything went okay, run the command: docker ps. If configured correctly, we should see output similar to below showing our container is up, running, and ready to go!
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 31deadb66e07 redis "docker-entrypoint.s..." 28 minutes ago Up 28 minutes 0.0.0.0:6378->6379/tcp, :::6378->6379/tcp inspiring_vaughan
Now that Redis is set up (and running), Python is next.
Windows users can try using this link for installation: https://docs.python.org/3/using/windows.html#windows-full.
Mac and some Linux users can follow the instructions below.
python3 -version to make sure Python 3 is installed. If Python 3 is installed the version number should be shown after entering the command.
If for some reason it is not installed , Python can be downloaded with this link: https://www.python.org/downloads/
*Note: For the best results, use Python 3.10.0 (or newer), but older versions of Python 3 may work as well. However, Python 2 will absolutely break the code in this doc, so avoid that.
Now that Python is set up, let’s print something to the console to make sure everything is working.
Create a new file named pyredis.py and open it up with your favorite code editor.
Add the line:
print("Hello spherical origin of human life")
Save the file and run it by clicking a play button in your editor or going to the file location in a terminal and typing:
If the text prints out successfully then we’re in good shape and ready to get into what we all came for.
Python doesn’t support Redis out of the box, so we’ll need to add the very appropriately named “redis” library first.
Do this by adding:
import redis at the top of the file.
And use pip to install redis with this command in your terminal:
pip3 install redis
Then add the following code below our print line in pyredis.py (don’t worry, we’ll explain it below):
try: redisClient = redis.Redis(host = 'localhost', port = 6378) pingTest = redisClient.ping() if(pingTest == True): print("Connected To Redis!") else: print("Could not connect to Redis!") except Exception as ex: print("Something went wrong!") print(ex)
Save and run now and if everything worked out okay, in our output we should see:
Connected to Redis!
If we change the port to 6377 and run it again:
redisClient = redis.Redis(host = 'localhost', port = 6378)
Our error handler will say that it couldn’t connect to Redis and print what the issue was.
Let’s discuss a bit about what is happening here.
First, at the highest level, there’s try and except code. This will let us attempt something once, and if an error happens at any time while running the code, it will run whatever code is in the except block.
Try: #Trying running code here except Exception as ex: #Run this code if something goes wrong
The first line of the try block creates a variable that uses our imported redis library to create a client connection that can be used to interact with Redis. We add the string localhost (or you can use the number equivalent which is: 127.0.0.1) and the default port (6378).
redisClient = redis.Redis(host = 'localhost', port = 6378)
The next line creates a variable named “pingTest” to, you guessed it, do a ping command inside Redis to make sure the connection worked okay. This is done using our redisClient variable and using our“ping” method. Our pingTest variable will capture the output of a true or false Boolean value.
pingTest = redisClient.ping()
The last code in the try block will check the value of “pingTest.” If it’s true it will print that it was successful, and if it’s false it will print that it could not connect.
if(pingTest == True): print("Connected To Redis!") else: print("Could not connect to Redis!")
In the except block, if any error is thrown while running the code above, it will grab the error, and instead of just stopping the program, let the user know that something unexpected happened with a dramatic message fit for such a perilous scenario. We will also give a bit more useful information by printing what Python says went wrong so that the error can be addressed.
Now that we can connect to Redis with Python, we can issue any commands we want!
Well, within reason, the advanced things are beyond the scope of this post, but let’s get our feet wet setting a value in Redis, getting that value from Redis again, and printing it using Python.
First, we’ll add the lines:
value = redisClient.get('dog') print(value)
We should see the output:
Connected To Redis! None
“None” is what Redis returned for the value “dog” because there wasn’t any value set for “dog” in Redis. None is a default null or empty value in Python.
Now let’s do this again, but we’ll set dog to “woof” first
Add the following lines:
redisClient.set('dog', 'woof!') value = redisClient.get('dog') print(value)
Run the program again and we’ll see the output:
Connected To Redis! None b'woof!'
The new line at the end that says b’woof!’ shows that we were successfully able to set and grab data from Redis.
Note the “b” before woof is Python telling you that the “value” variable is of type byte. That doesn’t mean too much for the scope of this writing. Just keep in mind that you may need to convert it to a string or other data type depending on if you want to do more in depth things with Python and Redis.
The next step is to add the line:
We are done because that’s it!
We have successfully used Python to interact with Redis by creating a client, issuing commands through that client to set a value from Redis, and getting a value back from Redis.
Keep in mind these are just the basics, but with this information, all sorts of possibilities are open for experimentation! For instance, you may want to make sure the Python script checks that the correct port is open, add a command line interface so it’s easier to use, or even create a dynamic caching solution for your series A startup. The sky’s the limit!
Here is our finished code:
try: redisClient = redis.Redis(host = 'localhost', port = 6378) pingTest = redisClient.ping() if(pingTest == True): print("Connected To Redis!") else: print("Could not connect to Redis!") except Exception as ex: print("Something went wrong!") print(ex) value = redisClient.get('dog') print(value) redisClient.set('dog', 'woof!') value = redisClient.get('dog') print(value)
Refactoring/Cleaning Up Our Code (Optional)
Now that we’re done, let’s clean this up a bit. This step is completely optional, but if you want to expand on this code in the future, it’ll be helpful to split this up into some reusable parts.
Here’s our cleaned-up code:
import redis def createRedisClient(host, port): try: redisClient = redis.Redis(host = host, port = port) pingTest = redisClient.ping() if(pingTest == True): print("Connected To Redis!") return redisClient else: print("Could not connect to Redis!") except Exception as ex: print("Could not connect to redis! See Message Below") print(ex) return False def getRedisValueByKey(key, redisClient): return redisClient.get(key) def setRedisKeyAndValue(key, value, redisClient): return redisClient.set(key, value) redisClient = createRedisClient('localhost', 6378) if(redisClient): value = getRedisValueByKey('dog', redisClient) print(value) value = setRedisKeyAndValue('dog', 'woof', redisClient) print(value) else: print("Count not get interact with redis")
Functionally the code is the same, but a few changes make expanding this program easier.
First, we can create a redisClient variable that can be used in multiple parts of the program and passed into methods.
Second, we can use methods that contain that redisClient variable to write code functionality once and reuse it.
For instance, if we want to add key values, or just get a value, we can reuse the new getRedisValueByKey and setRedisKeyAndValue functions instead of rewriting new code.
Finally, this update also does a better job of instructing the user on what the code is doing through the method names, reducing the need for comments.
And that’s it! If you made it this far, hopefully you enjoyed reading and coding along. Most importantly I hope you feel like a boss because you are! Enjoy the rest of your day/night!