Python-network-programming-python-connection-re-use
提供:Dev Guides
Python-接続の再利用
クライアントがサーバーに対して有効な要求を行うと、クライアント間で一時的な接続が確立され、送受信プロセスが完了します。 ただし、通信しているプログラム間で自動要求と応答が必要なため、接続を維持する必要があるシナリオがあります。 たとえば、インタラクティブなWebページをご覧ください。 Webページが読み込まれた後、フォームデータを送信するか、さらにCSSおよびJavaScriptコンポーネントをダウンロードする必要があります。 より高速なパフォーマンスとクライアントとサーバー間の途切れない通信のために、接続を維持する必要があります。
Pythonには、クライアントとサーバー間の接続の再利用を処理するメソッドを備えた urllib3 モジュールが用意されています。 以下の例では、接続を作成し、GET要求で異なるパラメーターを渡すことで複数の要求を作成します。 複数の応答を受け取りますが、プロセスで使用された接続の数もカウントします。 ご覧のように、接続の数は変わらず、接続の再利用を意味します。
from urllib3 import HTTPConnectionPool
pool = HTTPConnectionPool('ajax.googleapis.com', maxsize=1)
r = pool.request('GET', '/ajax/services/search/web',
fields={'q': 'python', 'v': '1.0'})
print 'Response Status:', r.status
# Header of the response
print 'Header: ',r.headers['content-type']
# Content of the response
print 'Python: ',len(r.data)
r = pool.request('GET', '/ajax/services/search/web',
fields={'q': 'php', 'v': '1.0'})
# Content of the response
print 'php: ',len(r.data)
print 'Number of Connections: ',pool.num_connections
print 'Number of requests: ',pool.num_requests
上記のプログラムを実行すると、次の出力が得られます-
Response Status: 200
Header: text/javascript; charset=utf-8
Python: 211
php: 211
Number of Connections: 1
Number of requests: 2