Python 请求 - 异常类型:ConnectionError - 尝试:除了不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21407147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:45:42  来源:igfitidea点击:

Python requests - Exception Type: ConnectionError - try: except does not work

pythonurlpython-requestsconnectionpython-2.x

提问by user1431148

I am using a webservice to retrieve some data but sometimes the url is not working and my site is not loading. Do you know how I can handle the following exception so there is no problem with the site in case the webservice is not working?

我正在使用网络服务来检索一些数据,但有时 url 不起作用并且我的网站没有加载。您知道我如何处理以下异常,以便在 Web 服务不工作的情况下网站没有问题吗?

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

I used

我用了

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)

but nothing happens

但什么也没发生

采纳答案by ProfHase85

You should not exit your worker instance sys.exit(1)Furthermore you 're catching the wrong Error.

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

What you could do for for example is:

例如,您可以做的是:

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"

In this case your program will continue, setting the value of rwhich usually saves the response to any default value

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