|
| 1 | +import typing as t |
| 2 | +from inspect import iscoroutinefunction |
| 3 | + |
| 4 | +from tenacity import ( |
| 5 | + retry as _retry, |
| 6 | + stop_after_attempt, stop_never, wait_fixed, |
| 7 | + retry_if_result, retry_if_exception_type |
| 8 | +) |
| 9 | + |
| 10 | +undefined = object() |
| 11 | + |
| 12 | + |
| 13 | +def retry(max_times: t.Optional[int] = None, |
| 14 | + wait_times: t.Optional[int] = None, |
| 15 | + retry_on_result=undefined, |
| 16 | + retry_on_exception: t.Union[ |
| 17 | + t.Type[BaseException], |
| 18 | + t.Tuple[t.Type[BaseException], ...], |
| 19 | + ] = Exception, |
| 20 | + *t_args, **t_kw): |
| 21 | + """ |
| 22 | + 包装tenacity.retry,让调用更简易些 |
| 23 | + :param max_times: 最大重试次数 |
| 24 | + :param wait_times: 每次重试等待时间 |
| 25 | + :param retry_on_result: 当返回值等于retry_on_result时,重试 |
| 26 | + :param retry_on_exception: 当抛出指定异常时,重试 |
| 27 | + :param t_args: tenacity.retry的参数 |
| 28 | + :param t_kw: tenacity.retry的参数 |
| 29 | + :return: |
| 30 | + """ |
| 31 | + |
| 32 | + stop_on = stop_never if max_times is None else stop_after_attempt(max_times) |
| 33 | + |
| 34 | + retry_on = retry_if_exception_type(retry_on_exception) |
| 35 | + if retry_on_result is not undefined: |
| 36 | + retry_on = retry_if_result(lambda result: result == retry_on_result) | retry_on |
| 37 | + |
| 38 | + wait_on = wait_fixed(wait_times) if wait_times is not None else wait_fixed(0) |
| 39 | + |
| 40 | + def decorator(func): |
| 41 | + |
| 42 | + if iscoroutinefunction(func): |
| 43 | + @_retry(retry=retry_on, stop=stop_on, wait=wait_on, *t_args, **t_kw) |
| 44 | + async def wrapper(*args, **kwargs): |
| 45 | + return await func(*args, **kwargs) |
| 46 | + |
| 47 | + return wrapper |
| 48 | + |
| 49 | + else: |
| 50 | + @_retry(retry=retry_on, stop=stop_on, wait=wait_on, *t_args, **t_kw) |
| 51 | + def wrapper(*args, **kwargs): |
| 52 | + return func(*args, **kwargs) |
| 53 | + |
| 54 | + return wrapper |
| 55 | + |
| 56 | + return decorator |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + @retry(max_times=3, wait_times=1, retry_on_result=None, retry_error_callback=lambda x: print("123")) |
| 61 | + async def maybe_none(): |
| 62 | + print("111111") |
| 63 | + return None |
| 64 | + |
| 65 | + |
| 66 | + import asyncio |
| 67 | + |
| 68 | + asyncio.run(maybe_none()) |
0 commit comments