一尘不染

在启动flask之前,如何检查redis是否正在运行(如果不是,请启动它)?

redis

我是Flask的新手,我想确保Redis服务器正在运行,如果没有运行,请启动它。这是我所拥有的:

@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)

但是,我收到一个错误“ OSError:[Errno 2]没有这样的文件或目录”

有没有更简单的方法来检查Redis服务器是否正在运行?


阅读 510

收藏
2020-06-20

共1个答案

一尘不染

使用 ping cmd的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)

样本输出:

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