當客戶端向伺服器發出有效請求時,它們之間將建立一個臨時連接以完成發送和接收過程。但是在某些情況下,由於正在通信的程式之間需要自動請求和回應,因此需要保持連接狀態。以一個互動式網頁為例。加載網頁後,需要提交表單數據或下載其他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
上一篇:
Python HTTP數據下載
下一篇:
Python網路介面