如何为urllib2.OpenDirector open()方法设置超时

时间:2012-07-03 23:07:07

标签: python settimeout urllib2

我正在使用一些urllib2.HTTPHandler子类作为socksipy project的代理。

除非他们点击挂起的网址,否则一切正常。全局和通过OpenDirector.open()方法设置超时不会执行任何操作。

以下是urllib2.HTTPHandlers:

# get the socksipy project code
import socks

class SocksiPyConnection(httplib.HTTPConnection):
    def __init__(self, proxytype, proxyaddr, proxyport = None, rdns = False, username = None, password = None, *args, **kwargs):
        self.proxyargs = (proxytype, proxyaddr, proxyport, rdns, username, password)
        httplib.HTTPConnection.__init__(self, *args, **kwargs)

    def connect(self):
        self.sock = socks.socksocket()
        self.sock.setproxy(*self.proxyargs)
        if isinstance(self.timeout, float):
            self.sock.settimeout(self.timeout)
        self.sock.connect((self.host, self.port))

class SocksiPyHandler(urllib2.HTTPHandler):
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kw = kwargs
        urllib2.HTTPHandler.__init__(self)

    def http_open(self, req):
        def build(host, port=None, strict=None, timeout=0):
            conn = SocksiPyConnection(*self.args, host=host, port=port, strict=strict, timeout=timeout, **self.kw)
            return conn
        return self.do_open(build, req)

我尝试将全局设置为 socket.setdefaulttimeout(30),但没有成功。当我在上面实例化 SocksiPyConnection 时,我也尝试设置超时。最后我尝试使用 OpenDirector.open 方法as the API says it takes a timeout设置超时但没有成功。

挂起的测试代码:

import sys
# import socksipy base code
sys.path.append( "/parent/path/to/socks.py" )
import socks 
import urllib2
import socket
socket.setdefaulttimeout(30)
proxyhost = "responder.w2"
proxyport = 1050
sys.path.append( "/home/gcorradini" )
from sock_classes import SocksiPyHandler
opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, proxyhost, int(proxyport)) )
resp = opener.open("http://erma.orr.noaa.gov/cgi-bin/mapserver/charts?version=1.1.1&service=wms&request=GetCapabilities", timeout=30.0)
# i just hang here forever

1 个答案:

答案 0 :(得分:0)

事实证明我上面提到的“挂起/超时”问题实际上是sockssipy socks.py代码中的“阻塞”问题。如果您正在命中仍然以200响应但没有发送数据(0字节)的端点,那么socks.py将阻止导致它的编写方式。这是创建自己的超时之前和之后:

socks.py之前

def __recvall(self, bytes):
    """__recvall(bytes) -> data
    Receive EXACTLY the number of bytes requested from the socket.
    Blocks until the required number of bytes have been received.
    """
    data = ""
    while len(data) < bytes:
       data = data + self.recv(bytes-len(data))
    return data

socks.py AFTER with timeout

def __recvall(self, bytes):
    """__recvall(bytes) -> data
    Receive EXACTLY the number of bytes requested from the socket.
    Blocks until the required number of bytes have been received.
    """
    data = self.recv(bytes, socket.MSG_WAITALL)
    if type(data) not in (str, unicode) or len(data) != bytes:
        raise socket.timeout('timeout')
    return data