注:使用此解决方案只有当你不能控制连接池的建设(如@ Jahaja的答案描述)。
问题是,urllib3
按需创建池。它调用不带参数的urllib3.connectionpool.HTTPConnectionPool
类的构造函数。课程在urllib3 .poolmanager.pool_classes_by_scheme
注册。诀窍是用你的类替换具有不同默认参数的类:
def patch_http_connection_pool(**constructor_kwargs):
"""
This allows to override the default parameters of the
HTTPConnectionPool constructor.
For example, to increase the poolsize to fix problems
with "HttpConnectionPool is full, discarding connection"
call this function with maxsize=16 (or whatever size
you want to give to the connection pool)
"""
from urllib3 import connectionpool, poolmanager
class MyHTTPConnectionPool(connectionpool.HTTPConnectionPool):
def __init__(self, *args,**kwargs):
kwargs.update(constructor_kwargs)
super(MyHTTPConnectionPool, self).__init__(*args,**kwargs)
poolmanager.pool_classes_by_scheme['http'] = MyHTTPConnectionPool
然后你可以调用来设置新的默认参数。确保在进行任何连接之前调用它。
patch_http_connection_pool(maxsize=16)
如果使用HTTPS连接,你可以创建一个类似的功能:
def patch_https_connection_pool(**constructor_kwargs):
"""
This allows to override the default parameters of the
HTTPConnectionPool constructor.
For example, to increase the poolsize to fix problems
with "HttpSConnectionPool is full, discarding connection"
call this function with maxsize=16 (or whatever size
you want to give to the connection pool)
"""
from urllib3 import connectionpool, poolmanager
class MyHTTPSConnectionPool(connectionpool.HTTPSConnectionPool):
def __init__(self, *args,**kwargs):
kwargs.update(constructor_kwargs)
super(MyHTTPSConnectionPool, self).__init__(*args,**kwargs)
poolmanager.pool_classes_by_scheme['https'] = MyHTTPSConnectionPool
这对我的作品。它应该被标记为正确答案。 – reish