简体   繁体   English

Python 请求未捕获 Internet 断开连接

[英]Python requests not catching internet disconnect

I'm using following code, to get a big API response using python requests library:我正在使用以下代码,使用 python 请求库获得大的 API 响应:

try : 
    r = requests.get("download_link")
    data = r.content
except requests.exceptions.ConnectionError as ex:
    print('Issue file download...'+str(ex))
except Exception as ex:
    print('Issue file download...'+str(ex))

Python requests version: 2.18.4, Python 请求版本:2.18.4,

Python version: 3-x Python 版本:3-x

Here the use case is, as soon as the API is called, I'm disconnecting the internet, and this is not throwing any error(program is stuck at the API call).这里的用例是,只要调用 API,我就会断开互联网,这不会引发任何错误(程序卡在 API 调用中)。 The API called would take 30+ secs to give complete response based on network speed, and there is high possibility of internet disconnection during this API call.调用的 API 需要 30 多秒才能根据网络速度给出完整的响应,并且在此 API 调用期间互联网断开的可能性很高。

I would like to catch error when internet disconnects during the API call.我想在 API 通话期间网络断开连接时捕获错误。 Could someone please guide me on how to handle it.有人可以指导我如何处理它。

Since requests >= 2.4.0 , you can use the timeout argument in seconds:由于requests >= 2.4.0 ,您可以以秒为单位使用 timeout 参数:

try : 
    timeout = 10
    r = requests.get("download_link", timeout=10)
    data = r.content
except requests.exceptions.ConnectionError as ex:
    print('Issue file download...'+str(ex))
except requests.exceptions.ReadTimeout as ex:
    print('Issue file download...'+str(ex))
except Exception as ex:
    print('Issue file download...'+str(ex))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM