Requests
:您不需要显式调用close()
。 request 完成后会自动关闭,因为它基于 urlopen (这就是为什么resp.raw.closed
是True),这是我观看后的简化代码session.py
and adapters.py
:
from urllib3 import PoolManager
import time
manager = PoolManager(10)
conn = manager.connection_from_host('host1.example.com')
conn2 = manager.connection_from_host('host2.example.com')
res = conn.urlopen(url="http://host1.example.com/",method="get")
print(len(manager.pools))
manager.clear()
print(len(manager.pools))
print(res.closed)
#2
#0
#True
然后做了什么__exit__
做?它用于清除PoolManager(self.poolmanager=PoolManager(...))
and proxy
.
# session.py
def __exit__(self, *args): #line 423
self.close()
def close(self): #line 733
for v in self.adapters.values():
v.close()
# adapters.py
# v.close()
def close(self): #line 307
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear()
那么什么时候你需要使用close()
,正如注释所说将连接释放回池中, 因为DEFAULT_POOLSIZE = 10
(http/https 是独立的)。这意味着如果您想在一个会话中访问 10 个以上的网站,您可以选择关闭一些您不需要的网站,否则当您有多个网站时,管理器将关闭从第一个到最新的连接。但实际上你不需要关心这个,你可以指定池大小,并且不会浪费太多时间来重建连接
aiohttp
aiohttp.ClientSession() 使用一个 TCPConnector 来处理所有请求。当它触发时__aexit__
, self._connector
将被关闭。
Edit: s.request()
已与主机建立连接,但未得到响应。await resp.text()
只能在得到响应后执行,如果您没有执行此步骤(等待响应),您将在没有响应的情况下退出。
if connector is None: #line 132
connector = TCPConnector(loop=loop)
...
self._connector = connector #line 151
# connection timeout
try:
with CeilTimeout(real_timeout.connect,loop=self._loop):
assert self._connector is not None
conn = await self._connector.connect(
req,
traces=traces,
timeout=real_timeout
)
...
async def close(self) -> None:
if not self.closed:
if self._connector is not None and self._connector_owner:
self._connector.close()
self._connector = None
...
async def __aexit__(self,
...) -> None:
await self.close()
这是显示我所说内容的代码
import asyncio
import aiohttp
import time
async def get():
async with aiohttp.ClientSession() as s:
# The response is already closed after this `with` block.
# Why would it need to be used as a context manager?
resp = await s.request('GET', 'https://www.stackoverflow.com')
resp2 = await s.request('GET', 'https://www.github.com')
print("resp:",resp._closed)
print("resp:",resp._connection)
print("resp2:",resp2._closed)
print("resp2:",resp2._connection)
s.close()
print(s.closed)
c = await resp.text()
d = await resp2.text()
print()
print(s._connector)
print("resp:",resp._closed)
print("resp:",resp._connection)
print("resp2:",resp2._closed)
print("resp2:",resp2._connection)
loop = asyncio.get_event_loop()
loop.run_until_complete(get()) # Python 3.5 +
#dead loop