Set timeout for xmlrpclib.ServerProxy

前端 未结 9 1691
轮回少年
轮回少年 2020-12-29 22:33

I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.

9条回答
  •  醉话见心
    2020-12-29 23:14

    I wanted a small, clean, but also explicit version, so based on all other answers here, this is what I came up with:

    import xmlrpclib
    
    
    class TimeoutTransport(xmlrpclib.Transport):
    
        def __init__(self, timeout, use_datetime=0):
            self.timeout = timeout
            # xmlrpclib uses old-style classes so we cannot use super()
            xmlrpclib.Transport.__init__(self, use_datetime)
    
        def make_connection(self, host):
            connection = xmlrpclib.Transport.make_connection(self, host)
            connection.timeout = self.timeout
            return connection
    
    
    class TimeoutServerProxy(xmlrpclib.ServerProxy):
    
        def __init__(self, uri, timeout=10, transport=None, encoding=None, verbose=0, allow_none=0, use_datetime=0):
            t = TimeoutTransport(timeout)
            xmlrpclib.ServerProxy.__init__(self, uri, t, encoding, verbose, allow_none, use_datetime)
    
    
    proxy = TimeoutServerProxy(some_url)
    

    I didn't realize at first xmlrpclib has old-style classes so I found it useful with a comment on that, otherwise everything should be pretty self-explanatory.

    I don't see why httplib.HTTP would have to be subclassed as well, if someone can enlighten me on this, please do. The above solution is tried and works.

提交回复
热议问题