Search code examples
pythonhttplib

How to handle timeouts with httplib (python 2.6)?


I'm using httplib to access an api over https and need to build in exception handling in the event that the api is down.

Here's an example connection:

connection = httplib.HTTPSConnection('non-existent-api.com', timeout=1)
connection.request('POST', '/request.api', xml, headers={'Content-Type': 'text/xml'})
response = connection.getresponse()

This should timeout, so I was expecting an exception to be raised, and response.read() just returns an empty string.

How can I know if there was a timeout? Even better, what's the best way to gracefully handle the problem of a 3rd-party api being down?


Solution

  • urllib and httplib don't expose timeout. You have to include socket and set the timeout there:

    import socket
    socket.settimeout(10) # or whatever timeout you want