defdo_retry(retry_times=FUNC_RETRIES, delay_seconds=FUNC_RETRY_DELAY_SECONDS): """ Decorator for function retry . @param retry_times: retry times @param delay_seconds: sleep time after per try @return: the return value of the called function @raise Exception: raises an exception when an error occurred after last time """ defdeco(f): @wraps(f) defwrapper(*args, **kwargs): _retry_times, _delay_seconds = retry_times, delay_seconds _err = None while _retry_times > 0: try: _err = None return f(*args, **kwargs) except RetryException as e: # e is a RetryException instance # so can call e.get_err() _err = e if _delay_seconds > 0: time.sleep(_delay_seconds) _retry_times -= 1 if _err: event = _err.get_err() print("_err-->", type(event), event) call_back(event)
return wrapper
return deco
那么, 在业务逻辑上需要进行重试的时候, 只需要加入这个装饰器即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
@do_retry(2, 10) # @run_time() # @run_time(10) deflogin(): rnt, res = http_post(url=url, data=data, headers=headers) if rnt > 0: # httpcode is NOT 200 # res: # error msg # type: dict raise RetryException(res, rnt) else: # httpcode 200 _json = res.json() # but response is not as expect if0 != _json.get("error_code"): event = self._buildup(_json) raise RetryException(event, rnt)