views:

50

answers:

1

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.

+2  A: 

The clean approach is to define and use a custom transport, e.g.:

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.HTTP(self.proxy, 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.

Alex Martelli