我一直用:
r = requests.get(url)
if r.status_code == 200:
# my passing code
else:
# anything else, if this even exists
现在我正在解决另一个问题并决定允许其他错误,现在我使用:
try:
r = requests.get(url)
r.raise_for_status()
except requests.exceptions.ConnectionError as err:
# eg, no internet
raise SystemExit(err)
except requests.exceptions.HTTPError as err:
# eg, url, server and other errors
raise SystemExit(err)
# the rest of my code is going here
除了可以在此级别测试各种其他错误之外,一种方法是否比另一种更好?
Response.raise_for_status() https://requests.readthedocs.io/en/latest/_modules/requests/models/#Response.raise_for_status只是一个用于检查状态代码的内置方法,其作用与第一个示例基本相同。
这里没有“更好”,只是关于流量控制的个人喜好。我更喜欢使用 try/ except 块来捕获任何调用中的错误,因为这会通知未来的程序员这些条件是某种错误。 if/else 不一定表示扫描代码时出现错误。
Edit:这是我的快速而肮脏的模式。
import time
from http import HTTPStatus
import requests
from requests.exceptions import HTTPError
url = "https://theurl.com"
retries = 3
retry_codes = [
HTTPStatus.TOO_MANY_REQUESTS,
HTTPStatus.INTERNAL_SERVER_ERROR,
HTTPStatus.BAD_GATEWAY,
HTTPStatus.SERVICE_UNAVAILABLE,
HTTPStatus.GATEWAY_TIMEOUT,
]
for n in range(retries):
try:
response = requests.get(url)
response.raise_for_status()
break
except HTTPError as exc:
code = exc.response.status_code
if code in retry_codes:
# retry after n seconds
time.sleep(n)
continue
raise
然而,在大多数情况下,我都会子类化requests.Session
, 进行定制HTTPAdapter
处理指数退避,上面的生活在一个重写的requests.Session.request
方法。可以看到一个例子here https://github.com/samamorgan/helpjuice/blob/master/helpjuice/client.py.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)