Python - How to check if Redis server is available
If you want to test redis connection once at startup, use the ping()
command.
from redis import Redis
redis_host = '127.0.0.1'
r = Redis(redis_host, socket_connect_timeout=1) # short timeout for the test
r.ping()
print('connected to redis "{}"'.format(redis_host))
The command ping()
checks the connection and if invalid will raise an exception.
- Note - the connection may still fail after you perform the test so this is not going to cover up later timeout exceptions.
The official way to check if redis server availability is ping ( http://redis.io/topics/quickstart ).
One solution is to subclass redis and do 2 things:
- check for a connection at instantiation
- write an exception handler in the case of no connectivity when making requests