简体   繁体   中英

Python requests not catching internet disconnect

I'm using following code, to get a big API response using python requests library:

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 version: 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). 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.

I would like to catch error when internet disconnects during the API call. Could someone please guide me on how to handle it.

Since requests >= 2.4.0 , you can use the timeout argument in seconds:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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