python-requests 必需如下使用才能保持keep-alive

python-requests 必需如下使用才能保持keep-alive


import requests

session = requests.session()

session.get('http://www.qq.com')
session.get('http://www.qq.com')

#输出如下
>>INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): www.qq.com
>>DEBUG:requests.packages.urllib3.connectionpool:"GET / HTTP/1.1" 200 None
>>DEBUG:requests.packages.urllib3.connectionpool:"GET / HTTP/1.1" 200 None

其官网提供的调试的方法是会产生新连接的,可以通过以下方法设置log为debug看到:

logging.BASIC_FORMAT = '%%(levelname)s - %(filename)s[%(lineno)d]- %(message)s'
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

# 第一次调用,log会输出创建一个新连接并放进连接池
requests.get('http://www.qq.com')

# 第二次调用,log依然输出创建一个新连接并放进连接池
requests.get('http://www.qq.com')


#输出如下:
>>INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): www.qq.com
>>DEBUG:requests.packages.urllib3.connectionpool:"GET / HTTP/1.1" 200 None
>>INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): www.qq.com
>>DEBUG:requests.packages.urllib3.connectionpool:"GET / HTTP/1.1" 200 None

Edit By MaHua

你可能感兴趣的:(python)