检查python中的超时错误

dip*_*rus 5 python exception python-2.7 python-requests

所以我在请求后有一个非常通用的日志语句:

try:
    r = requests.get(testUrl, timeout=10.0)
except Exception, err:
    logger.error({"message": err.message})
Run Code Online (Sandbox Code Playgroud)

这适用于我抛出的所有东西,除了TimeoutError.当请求超时时,我回来的是一个元组,它尝试并且无法序列化.

我的问题是我如何才能抓住这一类错误?对于初学者来说,TimeoutError这不是我有权访问的.我试过添加from exceptions import *但没有运气.我也尝试过导入,OSError因为文档说TimeoutError是子类,但TimeoutError导入后我无法访问OSError.

TimeoutError文档

我打算按顺序列出我的例外:

except TimeoutError, err:
     #handle this specific error
except Exception, err:
     #handle all other errors
Run Code Online (Sandbox Code Playgroud)

或者只是检查类型:

except Exception, err:
    if isinstance(err, TimeoutError):
        #handle specific error
    #handle all other errors
Run Code Online (Sandbox Code Playgroud)

Python 2.7.3和Django 1.5

ale*_*cxe 12

你可以处理requests.Timeout异常:

try:
    r = requests.get(testUrl, timeout=10.0)
except requests.Timeout as err:
    logger.error({"message": err.message})
except requests.RequestException as err:
    # handle other errors
Run Code Online (Sandbox Code Playgroud)

例:

>>> import requests
>>> url = "http://httpbin.org/delay/2"
>>> try:
...     r = requests.get(url, timeout=1)
... except requests.Timeout as err:
...     print(err.message)
... 
HTTPConnectionPool(host='httpbin.org', port=80): Read timed out. (read timeout=1)
Run Code Online (Sandbox Code Playgroud)

  • 专业提示:使用http://httpbin.org/来演示特定的响应行为.有一个`http:// httpbin.org/delay`路由,它会在可配置的延迟后响应. (4认同)