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__)
参考:
- CSDN-郭 璞偶遇不错的装饰器:本文主要参考,但是该文示例有点小 bug,进一步优化了一下
- SOF-UnboundLocalError: local variable 'e' referenced before assignment:这个问题解决了上面遇到的 bug ,
try...except
的机制,会有一个特殊的作用域的处理,会del e
- Python之旅-装饰器:复习了一下带参数装饰器的写法,本文就属于带参数的装饰器的用法