使用韧性装饰器时python3 try / except似乎失败

时间:2020-09-07 22:23:41

标签: python-3.x python-requests tenacity

试图获得与请求功能一起使用的坚韧性,以实现重试/退避,然后如果所有重试均失败,则返回HTTP状态。看来我可以使重试工作或使用try / except,但不能同时使用两者。包装其他功能没有帮助。

OSX mojave上的Python 3.7.7 要求2.24.0 韧性6.2.0

具有装饰器且不带try / except的功能1调用强度规则,但返回的错误不是http://

In [1330]: @retry(reraise=True,wait=wait_fixed(1), stop=stop_after_attempt(3))
      ...: def geturl(url):
      ...:     """
      ...:     get the url and raise http request errors for tenacity
      ...:     """
      ...:     print(datetime.now().strftime('%Y-%m-%d-%H:%M:%S'))
      ...:     headers = {'user-agent': 'my-app/0.0.1','Content-Type':'application/json'}
      ...:     data = {'name':'testcall','service':'armor'}
      ...:     r=None
      ...:     r = requests.post(url, data=json.dumps(data), headers=headers)
      ...:     r.raise_for_status()
      ...:     return r.status_code
      ...:

In [1331]: geturl(flakyurl)
2020-09-07-14:48:19
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): snout:7777
DEBUG:urllib3.connectionpool:http://snout:7777 "POST /flakyservice HTTP/1.1" 406 27
2020-09-07-14:48:20
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): snout:7777
DEBUG:urllib3.connectionpool:http://snout:7777 "POST /flakyservice HTTP/1.1" 405 27
2020-09-07-14:48:21
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): snout:7777
DEBUG:urllib3.connectionpool:http://snout:7777 "POST /flakyservice HTTP/1.1" 405 27
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
...

HTTPError: 405 Client Error: METHOD NOT ALLOWED for url: http://snout:7777/flakyservice

具有try / except的功能2会获得正确的错误,但无法调用强度

In [1332]: @retry(reraise=True,wait=wait_fixed(1), stop=stop_after_attempt(3))
      ...: def geturl3(url):
      ...:         print(datetime.now().strftime('%Y-%m-%d-%H:%M:%S'))
      ...:         headers = {'user-agent': 'my-app/0.0.1','Content-Type':'application/json'}
      ...:         data = {'name':'testcall','service':'armor'}
      ...:         r=None
      ...:         try:
      ...:             r = requests.post(url, data=json.dumps(data), headers=headers)
      ...:             r.raise_for_status()
      ...:             return 'sent', r.status_code
      ...:         except requests.exceptions.HTTPError as err:
      ...:             return 'http failed', err
In [1334]: geturl3(flakyurl)
2020-09-07-15:23:00
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): snout:7777
DEBUG:urllib3.connectionpool:http://snout:7777 "POST /flakyservice HTTP/1.1" 404 27
Out[1334]:
('http failed',
 requests.exceptions.HTTPError('404 Client Error: NOT FOUND for url: http://snout:7777/flakyservice'))

编辑: 解决方法是在发生异常后修复r.raise_for_status()-这会增强并捕捉坚韧性

1 个答案:

答案 0 :(得分:0)

已在编辑过的问题中回答: 解决方法是在发生异常后修复r.raise_for_status()-这会增强并捕捉坚韧性