Timeout for xmlrpclib client requests

Corey Goldberg picture Corey Goldberg · Mar 11, 2010 · Viewed 7.2k times · Source

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.

Answer

Alex Martelli picture Alex Martelli · Mar 11, 2010

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.