我正在使用 python 请求库(参见 here)创建下载服务,以从另一台服务器下载数据。问题是有时我会收到 503 错误
,我需要显示相应的消息。请参阅下面的示例代码:
import requests
s = requests.Session()
response = s.get('http://mycustomserver.org/download')
我可以从 response.status_code
检查并获得 status code = 200
。
但是我如何针对特定错误try/catch
,在这种情况下,我希望能够检测到503 错误
并适本地处理它们。
我该怎么做?
最佳答案
为什么不做
class MyException(Exception);
def __init__(self, error_code, error_msg):
self.error_code = error_code
self.error_msg = error_msg
import requests
s = requests.Session()
response = s.get('http://mycustomserver.org/download')
if response.status_code == 503:
raise MyException(503, "503 error code")
编辑:
似乎请求库也会使用 response.raise_for_status()
为您引发异常
>>> import requests
>>> requests.get('https://google.com/admin')
<Response [404]>
>>> response = requests.get('https://google.com/admin')
>>> response.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 638, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: Not Found
编辑2:
用下面的 try/except
包裹你 raise_for_status
try:
if response.status_code == 503:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 503:
#handle your 503 specific error
关于Python请求库异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24237185/