自己用装饰器写了一个,有什么需要改进的地方吗?
def retry(attempt):
def decorator(func):
def wrapper(*args, **kw):
att = 0
while att < attempt:
try:
return func(*args, **kw)
except Exception as e:
att += 1
return wrapper
return decorator
@rety(attempt=3)
def get_response(url):
import requests
r = requests.get('http://xxx')
return r.content
1
dalang 2015-04-21 13:24:14 +08:00
其实我觉得没什么问题。只是直接捕获 Exception 对后期排障有隐患,而且我更倾向于能明确告知调用者 retry 失败的原因。
def retry(attempt, raise_on_fail=False): def decorator(func): def wrapper(*args, **kw): att = 0 last_except = None while att < attempt: try: return func(*args, **kw) except Exception as e: att += 1 last_except = e else: if raise_on_fail: raise Exception('Hit retry threshold, failed for {0}' % str(last_except)) return None return wrapper return decorator |
2
dalang 2015-04-21 13:32:41 +08:00
|