Bootstrap FreeKB - Redis - Connect to Redis using Python
Redis - Connect to Redis using Python

Updated:   |  Redis articles

The redis module can be used to connect to a Redis cluster. pip install can be used to install the redis module.

pip install redis

 

And here is an example of how to connect to a Redis cluster. This is just the boilerplate code with no error handling.

#!/usr/bin/python3
import redis
client = redis.Redis(
        host="redis.example.com",
        port=6379,
        db=0)
client.ping()

 

Or like this, using from_url using "redis" (one trailing s) to connect to a Redis system that is NOT using SSL/TLS.

#!/usr/bin/python3
import redis
client = redis.Redis.from_url("redis://redis.example.com:6379")
client.ping()

 

Or using "rediss" (two trailing s) to connect to a Redis system that is using SSL/TLS.

#!/usr/bin/python3
import redis
client = redis.Redis.from_url("redis://redis.example.com:6379")
client.ping()

 

If the Redis system has SSL/TLS enabled, you may need to include ssl=True and perhaps ssl_cert_reqs="none".

#!/usr/bin/python3
import redis
client = redis.Redis(
        host="redis.example.com",
        port=6379,
        db=0,
        ssl=True,
        ssl_cert_reqs="none")
client.ping()

 

With a certiifcate chain.

#!/usr/bin/python3
import redis
client = redis.Redis(
        host="redis.example.com",
        port=6379,
        db=0,
        ssl=True,
        ssl_cert_reqs="required",
        ssl_certfile="cert.pem",
        ssl_keyfile="key.pem",
        ssl_ca_certs="ca.pem,
    )
client.ping()

 

If all goes well, the following should be returned.

It appears the connection to Redis was successful
client = Redis<ConnectionPool<Connection<host=my-redis-cluster.abc123.clustercfg.use1.cache.amazonaws.com,port=6379,db=0>>>
ping appears to have been successful
response = True

 

And here is an example with error handling.

#!/usr/bin/python3
import redis

try:
  client = redis.Redis(
        host="redis.example.com",
        port=6379,
        db=0,
        ssl=True)
except Exception as exception:
  print(f"got the following exception when trying to init the Redis client - {exception}")
else:
  print(f"redis.Redis.from_url appears to have been successful")
  print(f"client = {client}")

try:
  client.ping()
except Exception as exception:
  print(f"got the following exception when trying client.ping() - {exception}")
else:
  print(f"client.ping() appears to have been successful")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 7bbd7b in the box below so that we can be sure you are a human.