在Python“请求”模块中,如何检查服务器是否关闭或500?

TIM*_*MEX 3 python rest http

r = requests.get('http://example.com')
print str(r.status_code)
Run Code Online (Sandbox Code Playgroud)

我想检查我的服务器是否同时关闭或内部500错误。

如何使用请求检查两者?

Tho*_*zco 7

根据引发请求失败的原因,请求会引发不同类型的异常。

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` 
Run Code Online (Sandbox Code Playgroud)