我正在使用python请求库(请参见here)创建下载服务,以从另一台服务器下载数据。问题是有时我会收到503 error,并且需要显示适当的消息。请参见下面的示例代码:

import requests
s = requests.Session()
response = s.get('http://mycustomserver.org/download')

我可以从response.status_code检查并获得status code = 200
但是如何为特定错误添加try/catch,在这种情况下,我希望能够检测到503 error并进行适当处理。

我怎么做?

最佳答案

为什么不呢

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:

用以下raise_for_statustry/except包装起来
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

09-18 16:08