在python请求模块中保持活动状态
我有一个关于python请求模块的问题。根据文件 多亏了urllib3,keep alive在一个会话中是100%自动的!您在会话中发出的任何请求都将自动重用相应的连接 我的示例代码如下所示:在python请求模块中保持活动状态,python,http,python-requests,keep-alive,Python,Http,Python Requests,Keep Alive,我有一个关于python请求模块的问题。根据文件 多亏了urllib3,keep alive在一个会话中是100%自动的!您在会话中发出的任何请求都将自动重用相应的连接 我的示例代码如下所示: def make_double_get_request(): response = requests.get(url=API_URL, headers=headers, timeout=10) print response.text response = requests.get(
def make_double_get_request():
response = requests.get(url=API_URL, headers=headers, timeout=10)
print response.text
response = requests.get(url=API_URL, headers=headers, timeout=10)
print response.text
但我收到的日志告诉我,每个请求都会启动新的HTTP连接:
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): url
DEBUG:requests.packages.urllib3.connectionpool:"GET url HTTP/1.1" 200 None
response text goes here
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): url
DEBUG:requests.packages.urllib3.connectionpool:"GET url HTTP/1.1" 200 None
response text goes here
我做错什么了吗?通过使用wireshark查看数据包,似乎它们实际上已设置为保持活动 使用:
请求
顶级HTTP方法函数是一个方便的API,每次都会创建一个新的会话
对象,防止重复使用连接
从文件中:
会话对象允许您跨请求持久化某些参数。它还跨会话实例发出的所有请求持久化cookie,并将使用urllib3
的连接池
def make_double_get_request():
session = requests.Session()
response = session.get(url=API_URL, headers=headers, timeout=10)
print response.text
response = session.get(url=API_URL, headers=headers, timeout=10)
print response.text