我正在使用网络服务来检索一些数据,但有时网址无法正常工作且我的网站未加载。您知道我如何处理以下异常,以便在Web服务不工作的情况下网站没有问题吗?
Django Version: 1.3.1
Exception Type: ConnectionError
Exception Value:
HTTPConnectionPool(host='test.com', port=8580): Max retries exceeded with url:
我用过
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)
但没有任何反应
答案 0 :(得分:41)
您不应退出工作人员实例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"
在这种情况下,您的程序将继续,设置r
的值,通常会将响应保存为任何默认值