Python请求会话不继续创建连接而不重用连接

时间:2015-05-08 11:17:10

标签: python python-requests

我有以下代码:

protocol = "http"
if self.protocol == PROTOCOL_HTTPS:
  protocol = "https"
if self.session is None:
  self.session = Session()
  self.session.get(protocol+'://'+self.ip)
url = protocol+"://"+self.ip+requestURL
response = None
if requestType == GET_METHOD:
  response = self.session.get(url, headers=(header),stream=False)
elif requestType == POST_METHOD:
  response = self.session.post(url, payload, headers=(header), stream=False)

此代码有效但会打开与设备的连接太多。我只想在会话中打开一个连接。我尝试了以下代码,但它似乎不起作用。它仍然创建了多个连接。

adapter = requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=1)
self.session.mount('http://', adapter)
url = protocol+"://"+self.ip+requestURL
resp = self.session.get(url)

我做错了什么?

如何确保会话中只打开一个连接?

1 个答案:

答案 0 :(得分:0)

您不需要使用>>> import requests >>> s = requests.Session() >>> s.get('http://httpbin.org/get') 进行一次连接。 可以试试

<remove fileExtension=".woff" />
<remove fileExtension=".eot" />
<remove fileExtension=".ttf" />
<remove fileExtension=".svg" />

<mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
<mimeMap fileExtension=".ttf" mimeType="application/font-sfnt" />
<mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />

来自http://docs.python-requests.org/en/latest/api/#requests.Session