Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout for xmlrpclib client requests

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.

like image 905
Corey Goldberg Avatar asked Nov 27 '22 15:11

Corey Goldberg


1 Answers

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.

like image 123
Alex Martelli Avatar answered Nov 30 '22 04:11

Alex Martelli