r = requests.get('http://example.com')
print str(r.status_code)
我想检查我的服务器是向下还是内部500错误。
如何使用请求检查两者?
答案 0 :(得分:5)
请求会抛出不同类型的异常,具体取决于导致请求失败的原因。
import requests.exceptions
try:
r = requests.get('http://example.com')
r.raise_for_status() # Raises a HTTPError if the status is 4xx, 5xxx
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
print "Down"
except requests.exceptions.HTTPError:
print "4xx, 5xx"
else:
print "All good!" # Proceed to do stuff with `r`