代码之家  ›  专栏  ›  技术社区  ›  speedplane

在执行多个请求时如何加速python的urlib2

  •  20
  • speedplane  · 技术社区  · 15 年前

    我正在使用Python的URLLIB2库向特定主机发出几个HTTP请求。每次发出请求时,都会创建一个新的TCP和HTTP连接,这需要很长的时间。是否有任何方法可以使用urllib2保持TCP/HTTP连接的活动状态?

    3 回复  |  直到 9 年前
        1
  •  27
  •   tuxayo Corey Goldberg    9 年前

    如果你切换到 httplib ,您将对基础连接有更好的控制。

    例如:

    import httplib
    
    conn = httplib.HTTPConnection(url)
    
    conn.request('GET', '/foo')
    r1 = conn.getresponse()
    r1.read()
    
    conn.request('GET', '/bar')
    r2 = conn.getresponse()
    r2.read()
    
    conn.close()
    

    这将在同一基础TCP连接上发送2个HTTP GET。

        2
  •  2
  •   Greg Haskins    12 年前

    我用过第三方 urllib3 图书馆过去效果很好。它是为了补充 urllib2 通过共享连接以便重用。

    修改的示例来自 the wiki :

    >>> from urllib3 import HTTPConnectionPool
    >>> # Create a connection pool for a specific host
    ... http_pool = HTTPConnectionPool('www.google.com')
    >>> # simple GET request, for example
    ... r = http_pool.urlopen('GET', '/')
    >>> print r.status, len(r.data)
    200 28050
    >>> r = http_pool.urlopen('GET', '/search?q=hello+world')
    >>> print r.status, len(r.data)
    200 79124
    
        3
  •  0
  •   Collin Anderson    11 年前

    如果您需要比普通httplib更自动化的东西,这可能会有所帮助,尽管它不是线程安全的。

    try:
        from http.client import HTTPConnection, HTTPSConnection
    except ImportError:
        from httplib import HTTPConnection, HTTPSConnection
    import select
    connections = {}
    
    
    def request(method, url, body=None, headers={}, **kwargs):
        scheme, _, host, path = url.split('/', 3)
        h = connections.get((scheme, host))
        if h and select.select([h.sock], [], [], 0)[0]:
            h.close()
            h = None
        if not h:
            Connection = HTTPConnection if scheme == 'http:' else HTTPSConnection
            h = connections[(scheme, host)] = Connection(host, **kwargs)
        h.request(method, '/' + path, body, headers)
        return h.getresponse()
    
    
    def urlopen(url, data=None, *args, **kwargs):
        resp = request('POST' if data else 'GET', url, data, *args, **kwargs)
        assert resp.status < 400, (resp.status, resp.reason, resp.read())
        return resp
    
    推荐文章