Bra*_*mon 4 python python-requests aiohttp python-3.7
我对需要有点糊涂了.close()两个响应对象requests和aiohttp.(请注意,这是一个单独的实例方法,而不是 - session.close()我在谈论响应对象本身.)
Response(requests)或ClientResponse(aiohttp)在任何时候需要显式调用.close()?async with session.request('GET', 'https://www.pastebin.com')下面.)为什么要定义两个dunder方法,如果它被隐式关闭,如下所示?一些简单的测试(下面)似乎暗示响应在Session上下文管理器中定义时会自动关闭. (这本身调用self.close()中__exit__或__aexit__但这是会话,而不是Response对象的关闭.)
requests>>> import requests
>>>
>>> with requests.Session() as s:
... resp = s.request('GET', 'https://www.pastebin.com')
... resp.raise_for_status()
... print(resp.raw.closed) # `raw` is urllib3.response.HTTPResponse object
... print(resp.raw._pool)
... print(resp.raw._connection)
... c = resp.text
...
True
HTTPSConnectionPool(host='pastebin.com', port=443)
None
>>>
>>> while 1:
... print(resp.raw.closed)
... print(resp.raw._pool)
... print(resp.raw._connection)
... break
...
True
HTTPSConnectionPool(host='pastebin.com', port=443)
None
Run Code Online (Sandbox Code Playgroud)
aiohttp>>> import asyncio
>>> import aiohttp
>>>
>>> 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.pastebin.com')
... print(resp._closed)
... print(resp._connection)
... print(resp._released)
... c = await resp.text()
... print()
... print(resp._closed)
... print(resp._connection)
... print(resp._released)
... return c
...
>>> c = asyncio.run(get()) # Python 3.7 +
False
Connection<ConnectionKey(host='pastebin.com', port=443, is_ssl=True, ssl=None, proxy=None, proxy_auth=None, proxy_headers_hash=None)>
False
True
None
False
Run Code Online (Sandbox Code Playgroud)
这是源的requests.models.Response.什么"通常不需要明确调用"是什么意思?有什么例外?
def close(self):
"""Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
"""
if not self._content_consumed:
self.raw.close()
release_conn = getattr(self.raw, 'release_conn', None)
if release_conn is not None:
release_conn()
Run Code Online (Sandbox Code Playgroud)
Requests:你不需要明确地调用close().请求将自动关闭后完成,因为它立足于的urlopen(这就是为什么resp.raw.closed为真),这是简化的代码后,我看了session.py和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
Run Code Online (Sandbox Code Playgroud)
然后做了__exit__什么?它用来清除PoolManager(self.poolmanager=PoolManager(...))和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()
Run Code Online (Sandbox Code Playgroud)
所以什么时候需要使用close(),因为说明释放连接回池,因为DEFAULT_POOLSIZE = 10(http/https是独立的).这意味着如果您想通过一个会话访问超过10个网站,您可以选择关闭一些您不需要的网站,否则当您还有一个时,管理员将关闭从第一个到最新的连接.但实际上你不需要关心这个,你可以指定池大小,并且不会浪费太多时间来重建连接
aiohttpaiohttp.ClientSession()正在为所有请求使用一个TCPConnector.当它被触发时__aexit__, self._connector将被关闭.
编辑: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()
Run Code Online (Sandbox Code Playgroud)
这是显示我所说的代码
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
Run Code Online (Sandbox Code Playgroud)