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

 死神邀请我 发布于 2023-01-30 19:18

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

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)

但没有任何反应

1 个回答
  • 您不应该退出您的工作器实例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通常会将响应保存到任何默认值

    2023-01-30 19:22 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有