如何针对 python 请求的不同情况使用例外
How to use exceptions for different cases with python requests
我有这个代码
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
下会涵盖哪些代码
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
requests 在您的请求对象中有一个名为 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)
因此,考虑到上述情况,您现在可以在条件语句中使用状态代码
我有这个代码
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
下会涵盖哪些代码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
requests 在您的请求对象中有一个名为 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)
因此,考虑到上述情况,您现在可以在条件语句中使用状态代码