from retrying import retry
@retry(stop_max_attempt_number=3, wait_fixed=2000)
# 遇到异常将重试-stop_max_attempt_number=3 最大重复次数
# wait_fixed = 2000 重复间隔等待睡眠时间
def get_data_uploading():
url = 'http://192.168.0.12t'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
print(headers[0])
return
if __name__ == '__main__':
get_data_uploading()
如上所见,默认行为是无需等待就永远重试。
@retry def never_give_up_never_surrender(): print "Retry forever ignoring Exceptions, don't wait between retries"
让我们少一点坚持,并设置一些界限,如放弃前的尝试次数。
@retry(stop_max_attempt_number=7) def stop_after_7_attempts(): print "Stopping after 7 attempts"
我们没有一整天的时间,所以让我们设定一个边界,我们应该重新尝试多久的东西。
@retry(stop_max_delay=10000) def stop_after_10_s(): print "Stopping after 10 seconds"
大多数事情不喜欢被调查得尽可能快, 所以让我们在重述之间等待 2 秒。
@retry(wait_fixed=2000) def wait_2_s(): print "Wait 2 second between retries"
有些东西在注射一点随机性时表现最好。
@retry(wait_random_min=1000, wait_random_max=2000) def wait_random_1_to_2_s(): print "Randomly wait 1 to 2 seconds between retries"
话又说回来, 在重试分布式服务和其他远程端点时, 很难击败指数级的后退。
@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) def wait_exponential_1000(): print "Wait 2^x * 1000 milliseconds between each retry, up to 10 seconds, then 10 seconds afterwards"
我们有一些选择来处理提出特定或一般例外的复述,如这里的案例。
def retry_if_io_error(exception): """Return True if we should retry (in this case when it's an IOError), False otherwise""" return isinstance(exception, IOError) @retry(retry_on_exception=retry_if_io_error) def might_io_error(): print "Retry forever with no wait if an IOError occurs, raise any other errors" @retry(retry_on_exception=retry_if_io_error, wrap_exception=True) def only_raise_retry_error_when_not_io_error(): print "Retry forever with no wait if an IOError occurs, raise any other errors wrapped in RetryError"
我们还可以使用函数的结果来改变重试的行为。
def retry_if_result_none(result): """Return True if we should retry (in this case when result is None), False otherwise""" return result is None @retry(retry_on_result=retry_if_result_none) def might_return_none(): print "Retry forever ignoring Exceptions with no wait if return value is None"
任何停止,等待等的组合也支持给你的自由混合和匹配。
官方文档:重试 »皮皮 (pypi.org)