Python 装饰器实例

retry

偶然看到一篇文章,想到了前几天的一个需求,git pull性能不稳,需要加入重试机制,正好这个装饰器的实例符合这样的场景。

# coding:utf-8
import time
import logging
import socket
from functools import wraps
logging.basicConfig(level=logging.DEBUG)


def retry(retries=3, delay=1):
    def wrapper(func):
        @wraps(func)
        def proxy(*args, **kwargs):
            count = retries
            error = None
            while count > 0:
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print("relay times: {}".format(count))
                    count -= 1
                    time.sleep(delay)
                    error = e
            print(u"have retry {} times, but happen error: {}".format(count, error))
            return error
        return proxy
    return wrapper



@retry(2, 3)
def check():
    sk = socket.socket()
    sk.settimeout(5)
    sk.connect(('x.x.x.x', 80))
    
'''
# 上面写法属于简写方式,等价于下面的处理
maketry=retry(2,3)
@maketry
def check():
    pass
'''

if __name__ == "__main__":
    check()
    print(check.__name__)

参考:

上一篇:tenacity 重试


下一篇:疑难杂症篇(十)--Catia软件出现“没有合适的许可证来实现xx的请求”解决方案