Redis is a open-source, in-memory database storing data as key-value pairs. It is a popular choice as a caching mechanism or a message broker.
Redis can perform swift and memory-efficient operations with minimal configurations when paired with a language like Python.
Requirements
This article assumes you have the latest version of the Redis server, and Python 3 is installed and configured on your system.
We also assume basic Python and Redis knowledge.
Installing Redis-Py
To connect and use Redis with Python, we need a Python-Redis client. For this process, we will opt for redis-py as it is easy to use and configure.
You can check other python-redis clients on the resource page below:
https://redis.io/clients#python
To install, open the terminal and run the following command:
The previous command should download and install the Redis-py client.
Connecting to Redis
The next step is to connect to our Redis server. Start by creating a working directory as:
$ cd redis-python
Create a Python file and give it any name you see fit.
Open the file with your text editor and add the code shown below:
r = redis.Redis(
host='172.31.226.228',
port=6379,
password='password'
)
In the previous example code, we start by importing the Redis module.
Next, we create a new Redis client using the redis.Redis method. Then, we pass the parameters to connect to the Redis server.
NOTE: Ensure to replace the host, port, and password with the details for your Redis server.
To test the server is running, add the following:
print("PONG")
else:
print("Connection failed!")
Redis Set Key-Value Pairs
Once you are connected, you can perform all supported operations on the Redis server. For simplicity, let us set a new key-value pair.
We can run the code as:
r.set("mykey", "myvalue")
The set function takes key and value as arguments and adds them to the database.
Redis Get Key-Value Pairs
To get the value associated with a specific key, use the get method as shown below:
print(r.get("mykey"))
The previous code should return:
Python Redis SETEX
We can also set a key and value pair that expires at a specific duration. To do this, we can use the SETEX function as shown below:
r.setex("another-key", 60, "another-value")
Here, we set a new key and value that expires in 60 seconds.
To check the TTL, we can do the following:
This should return how many seconds the key has to live.
Redis Python Switch Database
To switch Redis databases in Python, use the select function as:
r.select(10)
The previous command should switch to the database at index 10.
Conclusion
This guide covered the basics of connecting and using Redis with Python through the Redis set key-value pairs and the Python Redis SETEX. We hope you found this article helpful. Check the other Linux Hint articles for tips and tutorials.