URLLib3连接池仅创建一个池

时间:2015-03-25 22:35:34

标签: python connection-pooling urllib3

目前我正在尝试抓一个网站,但该网站不允许超过100个请求一个TCP连接。所以,我试图为请求创建多个连接池。我尝试了以下代码。它不应该创建15个连接池吗?

from urllib3 import HTTPConnectionPool
for i in range(15):
    pool = HTTPConnectionPool('ajax.googleapis.com', maxsize=15)
    for j in range(15):
        resp= pool.request('GET', '/ajax/services/search/web')
    pool.num_connections

pool.num_connection始终打印1

2 个答案:

答案 0 :(得分:0)

问题是请求是一个接一个同步发出的。 因此,池将始终使用相同的连接,无需创建任何其他连接。

现在假设我们使用线程运行代码,将同时发出多个请求。 在这种情况下,pool.num_connections 将大于 1:

from concurrent.futures.thread import ThreadPoolExecutor

from urllib3 import HTTPConnectionPool


pool = HTTPConnectionPool('ajax.googleapis.com', maxsize=15)

def send_request(_):
    pool.request('GET', '/ajax/services/search/web')
    print(pool.num_connections)


with ThreadPoolExecutor(max_workers=5) as executor:
    executor.map(send_request, range(5))

答案 1 :(得分:-1)

如果您需要每100个请求关闭套接字,那么您需要手动执行此操作。这是一个每5个请求关闭所有套接字的示例:

import urllib3
urllib3.add_stderr_logger() # This lets you see when new connections are made

http = urllib3.PoolManager()
url = 'http://ajax.googleapis.com/ajax/services/search/web'
for j in range(15):
    resp = http.request('GET', url)
    if j % 5 == 0:
        # Reset the PoolManager's connections.
        # This might be overkill if you need more granular control per-host.
        http.clear()

您可以使用HTTPConnectionPool执行类似操作,并在使用新.close()替换它之前执行HTTPConnectionPool。我希望尽可能使用PoolManager(通常没有缺点)。

如果您希望获得超级粒度的关联,则可以使用pool._get_conn().close()手动从{{1}}开始连接。< / p>

相关问题