- Redis python | How to interact with redis using python in 2022
- Redis python client
- Redis python example
- Python redis auth
- python redis basis auth
- python redis auth using username and password
- python redis SSL enabled auth
- Redis python insert a key
- Redis python get a key
- Redis python get all keys
- Redis python scan
- Redis python pipeline
- Redis python additional resources
- Python redis github
- Python redis pypi
- Conclusion
- How to Use Redis With Python
- Requirements
- Installing Redis-Py
- Connecting to Redis
- Redis Set Key-Value Pairs
- Redis Get Key-Value Pairs
- Python Redis SETEX
- Redis Python Switch Database
- Conclusion
- About the author
- John Otieno
- Python Redis Set Commands
- Setting up Redis
- Installing Redis Modules
- Writing the Code
- Writing the Code
- Set Add
- Set Cardinality (Size)
- Set Difference
- Set Intersection
- Set Union
- Set Is Member and Multiple is Members
- Set Members
- Set Remove
Redis python | How to interact with redis using python in 2022
Redis is one of the most popular open-source key-value type storage. A user can interact with redis using multiple languages. In this tutorial, we will learn about the redis python client. We will understand how to interact with redis using python. so let’s get started.
Redis python client
redis-py is the python client a user can use to interact with redis. redis-py requires a running Redis instance so please make sure redis is running in your system. You can follow my tutorial to install redis on your system.
To install the redis-py type the below command
Now, connect to the python shell and type the below command to verify if the installation is successful.
If you are able to import the packages without any error it means the installation is successful.
Redis python example
In this session, we will understand how to interact with redis using python and perform various operations on the redis data.
Python redis auth
python support authentication to redis using basic auth, user, and pass auth as well as auth in the SSL-enabled environment.
python redis basis auth
To authenticate to redis we need to pass the redis host, port, and database to connect to. In most cases, the database is db0. You can follow the below tutorial to understand the redis databases.
In this case, the redis runs on host 127.0.0.1 and port 6379. Now type the below command to authenticate to redis.
import redis r = redis.Redis(host='localhost', port=6379, db=0)
python redis auth using username and password
If the redis is configured to connect using username and password, then type the below command to connect to redis
redis.Redis(host='localhost', port=6380, username='', password='<>pswd')
python redis SSL enabled auth
If the redis instance is configured with SSL, then we need to pass the ca certificate along with the host and port to connect to redis.
r = redis.Redis(host='127.0.0.1', port=6379, db=0, ssl=True, ssl_ca_certs='')
Redis python insert a key
To insert a key into the redis using python a user needs to use the set command
If you are getting TRUE as output, it means the key is successfully inserted.
Redis python get a key
get command is used to retrieve a particular key from the redis database.
Redis python get all keys
A user can also get all the keys present in redis using the get command.No need to pass any argument in the get command to get all the keys
Redis python scan
The scan is another powerful command that exists in redis. For SCAN/SSCAN/HSCAN/ZSCAN command, py-redis has implemented similar commands which are scan_iter/sscan_iter/hscan_iter/zscan_iter.
Now let’s use the scan_iter command to retrieve all the keys from the redis database.
for key, value in (('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')): r.set(key, value) for key in r.scan_iter(): print(key, r.get(key))
Redis python pipeline
The pipeline is a method using which we can run multiple commands at once without waiting for the response to each command. This improves the redis performance.
The same can be achieved using the redis python client. Below is a simple example of the redis pipeline.
pipe = r.pipeline() pipe.set('key_1', "value1") pipe.set('key_2', "value2") pipe.set('key_3', "value3") pipe.execute()
Redis python additional resources
You can check the below additional resources to learn more about the redis python client.
Python redis github
Check the redis python GitHub page to understand how the redis python library is written and check the readme for a quick overview of the redis client.
Python redis pypi
Check the Python redis PyPI official doc for some advanced redis python client library usage.
Conclusion
I hope you have liked this brief tutorial on the redis python client. Please do let me know if you are facing any issues while following along
How to Use Redis With Python
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:
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:
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:
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:
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.
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:
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:
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:
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.
About the author
John Otieno
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list
Python Redis Set Commands
Sets are lists filled with unique items. The set data type is helpfuly when you want to work with unique data types, thus they help with features where you want to easily deuplicate values. In this article, we will learn how to work with sets in Redis and Python.
Setting up Redis
For setting up Redis, I would recommend using a service for you in prod. Azure for example, has a great redis service that scales easily. However, you will want to learn redis and eventually how to scale it yourself. This will help with debugging cloud services or eventually, saving money and not using them.
We will start our intro to redis via using docker compose. Create a docker-compose.yml file and add the following.
version: "3.2" services: redis: image: "redis:alpine" command: redis-server ports: - "6379:6379" volumes: - $PWD/redis-data:/var/lib/redis - $PWD/redis.conf:/usr/local/etc/redis/redis.conf environment: - REDIS_REPLICATION_MODE=master
Ensure you have docker installed and run
Installing Redis Modules
In python, the main used redis module is called redis-py and can be installed using the follows.
Writing the Code
Let’s open up a new file, index.py and go through many of the common commands you will used with lists in redis.
Writing the Code
Let’s open up a new file, index.py and go through many of the common commands you will used with lists in redis.
Set Add
We can push items to a list using lpush . The first param is the name of the key and then we can pass in as many items as we want for the list.
# Set Add res = r.sadd("users", "user1") print(res)
For each of the example below, I will use the following template to run all the commands. Here is my full index.js file. We will just replace the commands each time.
import redis r = redis.Redis(host='localhost', port=6379, db=0) # Set Add res = r.sadd("users", "user1") print(res)
Set Cardinality (Size)
If we want to get the size of our set, we can use scard .
# Set Cardinaility const result = r.scard("users") print(result) # output: 2
Set Difference
We can get the difference or the values that are not in both sets using the sdiff command. This can be helpful for tracking usage metrics.
r.sadd("users-feature1", "user1", "user2") r.sadd("users-feature2", "user1") # Set Difference const result = r.sdiff("users-feature1", "users-feature2") print(result) # output: ["user2"]
Set Intersection
Similar to above, we can get the intersection between two sets, the values that are in both sets, using the SINTER command.
r.sadd("users-feature1", "user1", "user2") r.sadd("users-feature2", "user1") # Set Intersection const result = r.sinter("users-feature1", "users-feature2") print(result) # output: ["user1"]
Set Union
Keeping with the theme of set operations, we can take the union of two sets, returning a combination of sets, using the SUNION command.
r.sadd("users-feature1", "user1", "user2") r.sadd("users-feature2", "user1", "user3") # Set Union const result = r.sunion("users-feature1", "users-feature2") print(result) # output: ["user1", "user2", "user3"]
Set Is Member and Multiple is Members
We can check if a key is a member of a set using the SISMEMBER command.
r.sadd("users", "user1", "user2") # Set Is Member const result = r.sismember("users", "users1") print(result) # output: true
We can check multiple members (if you use redis 6 or later) with the SMISMEMBER which means Set Multiple Is Member.
r.sadd("users", "user1", "user2") # Set Multiple Is Member const result = r.sismember("users", "users1", "user2", "user3") print(result) # output: [true, true, false]
Set Members
To get a list of all members, we can use the SMEMBERS command.
r.sadd("users", "user1", "user2") # Set Members const result = r.smembers("users") print(result) # output: ["user1", "user2"]
Set Remove
We can remove a member from one set to another using the SREM command.
r.sadd("users", "user1", "user2") # Set Remove r.srem("users", "user1") const result = r.smembers("users") print(result) # output: ["user2"]