pythonredis

Python - How to check if Redis server is available


I'm developing a Python Service(Class) for accessing Redis Server. I want to know how to check if Redis Server is running or not. And also if somehow I'm not able to connect to it.

Here is a part of my code

import redis
rs = redis.Redis("localhost")
print rs

It prints the following

<redis.client.Redis object at 0x120ba50>

even if my Redis Server is not running.

As I found that my Python Code connects to the Server only when I do a set() or get() with my redis instance.

So I dont want other services using my class to get an Exception saying

redis.exceptions.ConnectionError: Error 111 connecting localhost:6379. Connection refused.

I want to return proper message/Error code. How can I do that??


Solution

  • 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:

    1. check for a connection at instantiation
    2. write an exception handler in the case of no connectivity when making requests