我一直使用:
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
除了可以在此级别测试各种其他错误之外,其中一种方法是否比另一种方法更好?
发布于 2020-04-28 00:20:34
Response.raise_for_status()
只是一种检查状态码的内置方法,其功能与第一个示例基本相同。
这里没有“更好的”,只是关于流程控制的个人偏好。我倾向于使用try/except块来捕获任何调用中的错误,因为这会让未来的程序员知道这些条件是某种错误。If/else在扫描代码时不一定指示错误。
发布于 2020-12-20 07:52:58
Better有点主观;两者都可以完成工作。也就是说,作为一个相对缺乏经验的程序员,我更喜欢Try / Except
表单。对我来说,T / E
提醒我,请求并不总是给你你期望的东西(在某种程度上,if / else
不会--但那可能只是我)。
raise_for_status()
还允许您根据需要轻松地针对不同的错误类型(.HTTPError
、.ConnectionError
)实现任意多或任意少的不同操作。在我目前的项目中,我已经确定了下面的表单,因为我采取了相同的行动,无论原因是什么,但我仍然有兴趣知道原因:
try:
...
except requests.exceptions.RequestException as e:
raise SystemExit(e) from None
玩具实现:
import requests
def http_bin_repsonse(status_code):
sc = status_code
try:
url = "http://httpbin.org/status/" + str(sc)
response = requests.post(url)
response.raise_for_status()
p = response.content
except requests.exceptions.RequestException as e:
print("placeholder for save file / clean-up")
raise SystemExit(e) from None
return response, p
response, p = http_bin_repsonse(403)
print(response.status_code)
https://stackoverflow.com/questions/61463224
复制相似问题