xmlrpclib客户端请求超时

2024-05-14 15:53:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python的xmlrpclib向xml rpc服务发出请求。

有没有办法设置客户端超时,这样当服务器不可用时,我的请求不会永远挂起?

我知道我可以用socket.setdefaulttimeout()全局设置套接字超时,但这并不可取。


Tags: 服务器客户端xmlsocketrpc全局发出请求xmlrpclib
3条回答

doh,要在python2.6+中运行,请执行以下操作:

class HTTP_with_timeout(httplib.HTTP):
    def __init__(self, host='', port=None, strict=None, timeout=5.0):
        if port == 0: port = None
        self._setup(self._connection_class(host, port, strict, timeout=timeout))

    def getresponse(self, *args, **kw):
        return self._conn.getresponse(*args, **kw)

class TimeoutTransport(xmlrpclib.Transport):
    timeout = 10.0
    def set_timeout(self, timeout):
        self.timeout = timeout
    def make_connection(self, host):
        h = HTTP_with_timeout(host, timeout=self.timeout)
        return h

为什么不:

class TimeoutTransport(xmlrpclib.Transport):

def setTimeout(self, timeout):
    self._timeout = timeout

def make_connection(self, host):
    return httplib.HTTPConnection(host, timeout=self._timeout)

是吗?

毕竟,HTTPHTTPS似乎只不过是旧Python版本的兼容类。

清洁方法是定义和使用自定义传输,例如: ! 这只对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)

有一个在the docs中定义和使用自定义传输的示例,尽管它用于不同的目的(通过代理访问,而不是设置超时),但这段代码基本上是受该示例的启发。

相关问题 更多 >

    热门问题