A simple implementation of an adorner that automatically retries when the function performs an exception, supports controlling the maximum number of retries, each retry interval, and increments each retry interval.
Core code 20 lines not available, the latest code can be accessed from GitHub to get
https://github.com/blackmatrix7/matirx-tookit/blob/master/decorator/retry.py
#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2017/8/24 20:36#@Author: Blackmatrix#@Site:#@File: retry.py#@Software: Pycharm fromTimeImportSleep fromFunctoolsImportWraps__author__='Blackmatrix'"""A simple adorner that automatically retries when a function performs an exception"""defRetry (max_retries=5, delay=0, Step=0, sleep_func=sleep):"""a simple adorner that automatically retries when an exception occurs:p Aram Max_retries: Maximum number of retries:p Aram delay: Delay per retry, per second:p Aram step: Delay increment after each retry, per second :p Aram Sleep_func: The method of implementing the delay, which defaults to Time.sleep, in some asynchronous frameworks, such as tornado, using time.sleep will cause the entire thread to block and can pass in a custom method to implement the delay. : Return:""" defWrapper (func): @wraps (func)def_wrapper (*args, * *Kwargs): nonlocal delay, step, max_retries func_ex=None whileMax_retries >0:Try: returnFunc (*args, * *Kwargs)exceptException as EX:FUNC_EX=ex max_retries-= 1ifDelay > 0orStep >0:sleep_func (delay) Delay+=StepElse: RaiseFUNC_EXreturn_wrapperreturnwrapperif __name__=='__main__': Pass
A simple implementation of the Python retry adorner