本文介绍了Python使用韧性模块重试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难使韧性库正常工作.以下测试中的重试根本不会触发.我希望每5秒钟重试一次,日志文件会反映出重试次数.
I'm having having difficulty getting the tenacity library to work as expected. The retry in the following test doesn't trigger at all. I would expect a retry every 5 seconds and for the log file to reflect the retry attempts.
import paramiko
import tenacity
from configparser import RawConfigParser
import logging
def main():
parser = RawConfigParser()
parser.read('config.ini')
HOST = parser['SSH']['host']
PORT = parser['SSH']['port']
USER = parser['SSH']['user']
LOG_LEVEL = parser['Logging']['level']
LOG_FILE = parser['Files']['log_file']
LOG_FORMAT = parser['Logging']['format']
with open(LOG_FILE, "a") as f:
logging.basicConfig(filename=LOG_FILE,level=LOG_LEVEL,format=LOG_FORMAT)
logging.info("******Started logging******")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
@tenacity.retry(wait=tenacity.wait_fixed(5))
def connect():
try:
client.connect(HOST, int(PORT), USER)
logging.info("Successful connection to remote server")
except Exception:
logging.error("Cannot connect to remote server")
connect()
if __name__ == "__main__":
main()
日志文件将其吐出:
> 2017-11-04 19:55:20,695 ******Started logging******
> 2017-11-04 19:55:20,695 Cannot connect to remote server
推荐答案
我想tenacity
通过处理异常来检测故障.在您的代码中记录了异常,然后将其丢弃.因此,对于tenacity
,您的呼叫实际上是成功的.您应该重新引发此异常以获得预期的行为.像这样:
I suppose that tenacity
detects failures by handling exceptions. In your code the exception is logged and then discarded. So, for tenacity
, your call is actually successful. You should re-raise this exception to get the expected behavior. Like this:
@tenacity.retry(wait=tenacity.wait_fixed(5))
def connect():
try:
client.connect(HOST, int(PORT), USER)
logging.info("Successful connection to remote server")
except Exception:
logging.error("Cannot connect to remote server")
raise
这篇关于Python使用韧性模块重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!