To connect to a Redis server with Python, one can use python3-redis module.

First verify that python3-redis module is installed. I’m showing the package name in Fedora 39, if you use a different distro, then check for the relevant package name.

$ rpm -q python3-redis
python3-redis-4.3.3-1.el9.noarch

Here is the sample code to connect to a non-cluster Redis server:

import redis

# Connect to Redis
r = redis.Redis(host='10.97.147.175', port=6379)

# Set a key-value pair
r.set('my_key', 'Hello, Redis!')

# Get the value of the key
value = r.get('my_key')
print(value.decode('utf-8'))

If you want to connect to a Redis cluster (that has both master and replicas), use this version instead:

from redis.cluster import RedisCluster as Redis

# Connect to Redis
r = Redis(host='10.103.245.73', port=6379)

# Set a key-value pair
r.set('my_key', 'Hello, Redis!')

# Get the value of the key
value = r.get('my_key')
print(value.decode('utf-8'))

Note: a Redis cluster, is the cluster where you would need to run redis-cli -c -h server_name to connect.

I forgot where I got the original code snippet from, but I will update the reference if I find it out later.

Reference: