How do I check if redis is running before I start flask (and start it if it isn't)?

flask, python, redis

Solution

Use ping cmd of redis:

import redis
from redis import ConnectionError
import logging

logging.basicConfig()
logger = logging.getLogger('redis')

rs = redis.Redis("localhost")
try:
    rs.ping()
except ConnectionError:
    logger.error("Redis isn't running. try `/etc/init.d/redis-server restart`")
    exit(0)

Sample Output:

ERROR:redis:Redis isn't running. try `/etc/init.d/redis-server restart`

Problem

I am new to Flask and want to make sure the redis server is running and start it if it isn't. Here's what I have: ``` @app.before_first_request def initialize(): cmd = 'src/redis-cli ping' p = subprocess.Popen(cmd,stdout=subprocess.PIPE) out, err = p.communicate() #if out.startswith('Could not connect to Redis'): #start redis here if err is not None: raise Exception(err) ``` However, I get an error "OSError: [Errno 2] No such file or directory" Is there an easier way to check if the redis server is running?

Original source

Related problems