我实现了以下重试装饰器。
def retry(delay=10, retries=4):
def retry_decorator(f):
@wraps(f)
def f_retry(*args, **kwargs):
while retries > 1:
try:
return f(*args, **kwargs)
except Exception as e:
msg = "Exception: {}, Retrying in {} seconds...'.format(e, delay)"
print(msg)
time.sleep(delay)
retries -= 1
return f(*args, **kwargs)
return f_retry
return retry_decorator
我得到未定义重试的错误。但是,在函数定义中提到了重试。我无法弄清楚这里出了什么问题。任何帮助将不胜感激。
答案 0 :(得分:1)
我通过收集字典中的重试和延迟变量,然后在函数内部使用变量来使其工作。
def retry(delay=10, retries=4):
def retry_decorator(f):
@wraps(f)
def f_retry(*args, **kwargs):
opt_dict = {'retries': retries, 'delay': delay}
while opt_dict['retries'] > 1:
try:
return f(*args, **kwargs)
except Exception as e:
msg = "Exception: {}, Retrying in {} seconds...".format(e, delay)
print(msg)
time.sleep(opt_dict['delay'])
opt_dict['retries'] -= 1
return f(*args, **kwargs)
return f_retry
return retry_decorator