2013-08-27 12 views
32

(編集:おそらく、このエラーの意味は間違っています。これは、クライアントの接続プールがいっぱいであるか、SERVERの接続プールがいっぱいであり、クライアントのエラーです)Pythonの「要求」モジュールの接続プールサイズを変更できますか?

私はhttpのpython threadingrequestsモジュールを同時に使用して多数のリクエストを作成しようとしています。ログに次のエラーが表示されます。

WARNING:requests.packages.urllib3.connectionpool:HttpConnectionPool is full, discarding connection: 

要求の接続プールのサイズを大きくするにはどうしたらよいですか。

答えて

70

これはトリックを行う必要があります。

import requests 
sess = requests.Session() 
adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) 
sess.mount('http://', adapter) 
resp = sess.get("/mypage") 
+5

これは私の作品を。正解とマークする必要があります。 – reish

9

注:接続プールの建設を制御できない場合にのみは、このソリューションを使用する(@ 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 
+1

Requestsには、ConnectionPoolコンストラクタのパラメータを提供するための組み込みAPIがあり、コンストラクタのパッチは不要です。 (@ Jahajaの答えを参照してください) – shazow

+1

それは文脈によって異なります。 HTTPAdapterの作成を制御できる場合は、コンストラクターを使用することが適切なソリューションです。しかし、接続プールが、あるフレームワークやライブラリに深く埋め込まれたどこかで初期化されるケースがあります。そのような場合は、上記のようにライブラリをパッチしたり、接続プールのコンストラクタにパッチを当てたりすることができます。 –

+0

私は私の解決策に説明を加えました。 –