python装饰器
关于python装饰器的具体介绍,请看:
http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
淘宝的API是非常不稳定的,有时可以通过重试的方式进行处理。
有的API要获取很多页数据,通过一个page参数来指定获取第几页。
使用python 装饰器 构建一个重试机制
右边的比左边的健壮性要好很多
1 def tao_api_exception(MAX_RETRY_TIMES = 40): 2 3 def _wrapper_func(func): 4 5 def __wrapped_func(*args, **kwargs): 6 retry_times = 0 7 res = None 8 while True: 9 try: 10 res = func(*args, **kwargs) 11 except JsonDecodeException, e: 12 retry_times += 1 13 if retry_times > MAX_RETRY_TIMES: 14 raise TaoApiMaxRetryException("retry %i times ,but still failed"%MAX_RETRY_TIMES) 15 sleep(5) 16 continue 17 except ErrorResponseException,e: 18 retry_times += 1 19 20 return __wrapped_func 21 22 return _wrapper_func 23