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__)

参考:

posted @ 2019-03-03 18:31  Michael翔  阅读(188)  评论(0编辑  收藏  举报