13

我正在使用 urllib2 加载网页,我的代码是:

httpRequest = urllib2.Request("http:/www....com")
pageContent = urllib2.urlopen(httpRequest)
pageContent.readline()

如何获取要设置的套接字属性TCP_NODELAY

在普通套接字中,我将使用函数:

socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
4

3 回答 3

14

如果您需要访问所用套接字上的此类低级属性,则必须重载一些对象。

首先,您需要创建HTTPHandler的子类,在标准库中执行以下操作:

class HTTPHandler(AbstractHTTPHandler):

    def http_open(self, req):
        return self.do_open(httplib.HTTPConnection, req)

    http_request = AbstractHTTPHandler.do_request_

如您所见,它使用一个HTTPConnection打开连接...您也必须覆盖它;)以升级该connect()方法。

这样的事情应该是一个好的开始:

class LowLevelHTTPConnection(httplib.HTTPConnection):

    def connect(self):
        httplib.HTTPConnection.connect(self)
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)


class LowLevelHTTPHandler(HTTPHandler):

    def http_open(self, req):
        return self.do_open(LowLevelHTTPConnection, req)

urllib2 足够聪明,可以让你继承一些处理程序然后使用它,urllib2.build_opener就是为此而设计的:

urllib2.install_opener(urllib2.build_opener(LowLevelHTTPHandler)) # tell urllib2 to use your HTTPHandler in replacement of the standard HTTPHandler
httpRequest = urllib2.Request("http:/www....com")
pageContent = urllib2.urlopen(httpRequest)
pageContent.readline()
于 2013-07-26T13:10:12.117 回答
9

对于请求,类似乎在request.packages.urllib3; 有 2 个类,HTTPConnection 和 HTTPSConnection。它们应该可以在模块顶层进行monkeypatchable:

from requests.packages.urllib3 import connectionpool

_HTTPConnection = connectionpool.HTTPConnection
_HTTPSConnection = connectionpool.HTTPSConnection

class HTTPConnection(_HTTPConnection):
    def connect(self):
        _HTTPConnection.connect(self)
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

class HTTPSConnection(_HTTPSConnection):
    def connect(self):
        _HTTPSConnection.connect(self)
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

connectionpool.HTTPConnection = HTTPConnection
connectionpool.HTTPSConnection = HTTPSConnection
于 2013-07-30T15:53:11.670 回答
1

你必须使用urllib2吗?

或者,您可以使用设置了 TCP_NODELAY 选项的 httplib2。

https://code.google.com/p/httplib2/

它为您的项目添加了依赖项,但似乎没有猴子修补那么脆弱。

于 2013-08-01T00:50:41.507 回答