Python请求库异常处理

标签 python exception python-requests http-status-code-503

我正在使用 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/

相关文章:

Python检查列表中是否存在刮取的元素

python - 我是否在 Django 测试中 mock 这个辅助函数?

exception - 如何在c#中将null分配给可为空的字节

iOS CollectionView 'NSInternalInconsistencyException'

ssl - Python的默认SSL证书上下文在代理后面时不能在请求方法中工作,否则工作正常

python - 卡夫卡 : How to consume data based on Timestamp

python - 如何使用 REST 请求通过 python 脚本加载 Kibana 可视化

c# - 我自己的异常处理程序仍然抛出异常并使应用程序崩溃

python - 是否可以捕获请求的所有异常? (通常,对于模块)

curl - 将curl 转换为python 请求