@retry(retry_on_exception=if_value_error, stop_max_attempt_number=3, wait_random_min=1000, wait_random_max=3000) defrun(): value = random.randint(0, 10) msg = f'value is {value}' print(msg) if value <= 5: raise ValueError('value is too small!') else: raise Exception('value is too large!')
if __name__ == '__main__': run()
当函数run抛出ValueError异常时,则进行重试;抛出Exception异常时,不会重试。
5. 指定返回值重试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
from retrying import retry import random
defif_return_small(value): return value <= 5
@retry(retry_on_result=if_return_small, stop_max_attempt_number=3, wait_random_min=1000, wait_random_max=3000) defrun(): value = random.randint(0, 10) msg = f'value is {value}' print(msg) return value