我有这段代码
try:
response = requests.post(url, data=json.dumps(payload))
except (ConnectionError, HTTPError):
msg = "Connection problem"
raise Exception(msg)
现在我想要以下
if status_code == 401
login() and then try request again
if status_code == 400
then send respose as normal
if status_code == 500
Then server problem , try the request again and if not successful raise EXception
现在这些是状态代码,我不知道如何将状态代码与异常混合。我也不知道HttpError会涵盖哪些代码
答案 0 :(得分:2)
请求在您的请求对象中有一个名为raise_for_status
的调用,如果在400到500范围内返回任何代码,则会引发HTTPError
异常。
raise_for_status
的文档是here
所以,你可以做的,就是在你打电话之后:
response = requests.post(url, data=json.dumps(payload))
您拨打raise_for_status
作为
response.raise_for_status()
现在,您已经捕获了这个异常,这很好,所以您只需检查错误中的状态代码。您可以通过两种方式使用它。您可以从异常对象或请求对象中获取它。以下是此示例:
from requests import get
from requests.exceptions import HTTPError
try:
r = get('http://google.com/asdf')
r.raise_for_status()
except HTTPError as e:
# Get your code from the exception object like this
print(e.response.status_code)
# Or you can get the code which will be available from r.status_code
print(r.status_code)
因此,考虑到上述情况,您现在可以在条件语句中使用状态代码
答案 1 :(得分:1)
https://docs.python.org/2/library/urllib2.html#urllib2.URLError
code
An HTTP status code as defined in RFC 2616. This numeric value
corresponds to a value found in the dictionary of codes as found in
BaseHTTPServer.BaseHTTPRequestHandler.responses.
您可以从HTTPError
成员的code
获取错误代码,如此
try:
# ...
except HTTPError as ex:
status_code = ex.code