mat*_*szb 0 python http keep-alive python-requests
我对python-requests模块有疑问。根据文档
多亏了urllib3,保持活动状态在会话中是100%自动的!您在会话中发出的任何请求都将自动重用适当的连接!
我的示例代码如下所示:
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
Run Code Online (Sandbox Code Playgroud)
但是我收到的日志告诉我们,每个请求都会启动新的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
Run Code Online (Sandbox Code Playgroud)
难道我做错了什么?通过查看带有Wireshark的数据包,似乎实际上它们已经设置了保持活动状态。
使用Session()实例:
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
Run Code Online (Sandbox Code Playgroud)
所述requests顶层HTTP方法函数是一个方便的API,创建一个新的Session对象,每次,防止连接的重用。
从文档中:
通过Session对象,您可以在请求中保留某些参数。它还会在来自Session实例的所有请求中保留cookie,并将使用
urllib3的连接池。