I am using Python's xmlrpclib to make requests to an xml-rpc service.
Is there a way to set a client timeout, so my requests don't hang forever when the server is not available?
I know I can globally set a socket timeout with socket.setdefaulttimeout(), but that is not preferable.
The clean approach is to define and use a custom transport, e.g.: ! this will work only for python2.7 !
import xmlrpclib, httplib
class TimeoutTransport(xmlrpclib.Transport):
    timeout = 10.0
    def set_timeout(self, timeout):
        self.timeout = timeout
    def make_connection(self, host):
        h = httplib.HTTPConnection(host, timeout=self.timeout)
        return h
t = TimeoutTransport()
t.set_timeout(20.0)
server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=t)
There's an example of defining and using a custom transport in the docs, though it's using it for a different purpose (access via a proxy, rather than setting timeouts), this code is basically inspired by that example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With