Python网络编程

Python连接重用

Python连接重用详细操作教程
当客户端向服务器发出有效请求时,它们之间将建立一个临时连接以完成发送和接收过程。但是在某些情况下,由于正在通信的程序之间需要自动请求和响应,因此需要保持连接状态。以一个交互式网页为例。加载网页后,需要提交表单数据或下载其他CSS和JavaScript组件。需要保持连接状态以提高性能,并在客户端和服务器之间保持不间断的通信。
Python提供了urllib3模块,该模块具有一些方法来处理客户端和服务器之间的连接重用。在下面的示例中,我们通过在GET请求中传递不同的参数来创建连接并发出多个请求。我们收到了多个响应,但我们还计算了该过程中已使用的连接数。如我们所见,连接数没有改变,这意味着连接的重用。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
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
当执行上面示例代码,得到以下结果:
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
Response Status: 200
Header: text/javascript; charset=utf-8
Python: 211
php: 211
Number of Connections: 1
Number of requests: 2
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4