Basically from Python I am creating an instance of http.client.HTTPSConnection from an url address which is the remote server url in order to download a remote file:
try:
conn = http.client.HTTPSConnection(remoteServerUrl)
conn.request("GET", remoteFile)
# rest of code
except Exception as e:
print(e.message)
finally:
conn.close()
If I disconnect from internet (no internet connection) and I execute above code, when creating the instance of http.client.HTTPSConnection, it is not throwing any exception saying for example that the connection couldn’t be established with the remote server. Also the conn object looks like gets populated correctly. So when executing next line conn.request I get an exception at that moment but not before.
I would like to detect the error just when the instance is created and not having to wait until the request (conn.request) is done.
When the line of code conn.request is exectued it is throwing the following exception:
socket.gaierror: [Errno 11001] getaddrinfo failed
So how can I detect if I get a "correct" instance of http.client.HTTPSConnection without errors?
>Solution :
I would like to detect the error just when the instance is created …
The short answer is that you can’t. If you look at the source code, you will see that HTTPSConnection and HTTPConnection do almost nothing. They don’t even attempt to resolve the hostname in the URL.
The one thing that you could do is call connect() on the HTTPConnection or HTTPSConnection handle. This will attempt to resolve the hostname AND establish the network connection.
However, I don’t see how that gets you anywhere. Merely establishing the connection does not insulate you from (subsequent) network errors. And it certainly doesn’t insulate you from the many kinds of failures that can result from sending a request.