如何在启动烧瓶之前检查redis是否正在运行(如果不是,则启动它)? [英] How do I check if redis is running before I start flask (and start it if it isn't)?

查看:338
本文介绍了如何在启动烧瓶之前检查redis是否正在运行(如果不是,则启动它)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Flask的新手,想要确保redis服务器正在运行,如果没有,请启动它。以下是我的:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$'$ $ / redis-cli ping'
p = subprocess.Popen(cmd,stdout = subprocess.PIPE)
out,err = p.communicate()
#if out.startswith('Could not connect到redis'):#start redis here
如果err不是None:raise Exception(err)



然而,我得到一个错误OSError:[Errno 2]没有这样的文件或目录

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

解决方案

使用 ping cmd of redis:

 从redis导入redis 
导入ConnectionError
导入日志

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

rs = redis.Redis(localhost)
试试:
rs.ping()
,除了ConnectionError:
logger.error(Redis没有运行。尝试`/etc/init.d/redis-server restart`)
exit(0)

示例输出:

$ p $ 错误:redis:Redis不在运行试试`/etc/init.d/redis -server restart`


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?

解决方案

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`

这篇关于如何在启动烧瓶之前检查redis是否正在运行(如果不是,则启动它)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆