Python请求 - 异常类型:ConnectionError - try:except不起作用

use*_*148 25 python connection url python-2.x python-requests

我使用web服务来检索一些数据,但有时网址不起作用,我的网站没有加载.你知道我如何处理以下异常,所以如果webservice不工作,网站没有问题吗?

Django Version: 1.3.1 
Exception Type: ConnectionError
Exception Value: 
HTTPConnectionPool(host='test.com', port=8580): Max retries exceeded with url:
Run Code Online (Sandbox Code Playgroud)

我用了

try:
   r = requests.get("http://test.com", timeout=0.001)
except requests.exceptions.RequestException as e:    # This is the correct syntax
   print e
   sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

但没有任何反应

Pro*_*e85 51

您不应该退出您的工作器实例sys.exit(1) 此外您正在捕获错误的错误.

你可以做的例如是:

from requests.exceptions import ConnectionError
try:
   r = requests.get("http://example.com", timeout=0.001)
except ConnectionError as e:    # This is the correct syntax
   print e
   r = "No response"
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您的程序将继续,设置其值r通常会将响应保存到任何默认值

  • ConnectionError 也是一个内置错误类型的名称 - 当他们有如此可怕的命名实践时,它怎么能成为一个广泛使用的包呢?str 和 repr 都没有给出任何指示该类不是内置类。它甚至不继承自内置的 ConnectionError,而是继承自 OSError(真正的内置错误也是如此)。 (7认同)
  • 我刚尝试过,但结果相同. (2认同)
  • 有用!非常感谢!但我使用了 except requests.exceptions.ConnectionError 作为 e: (2认同)