Requests / aiohttp:关闭响应对象

时间:2018-11-01 14:37:40

标签: python python-requests aiohttp python-3.7

对于在.close()requests中都需要aiohttp一个响应对象的需求,我有些困惑。 (请注意,这是一个独立于session.close()的实例方法-我说​​的是响应对象本身。)

  • Responserequests)或ClientResponseaiohttp)是否需要显式调用.close()
  • 如果没有,使用响应本身作为上下文管理器的目的是什么? (下面的{async with session.request('GET', 'https://www.pastebin.com')。)为什么要隐式地关闭它,如下所示定义两个dunder方法?

一些简单的测试(如下所示)似乎暗示,在会话上下文管理器中定义响应后,它们会自动关闭。(其本身在self.close()中称为__exit____aexit__。但这是Session的关闭,而不是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

示例-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

这里是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()

1 个答案:

答案 0 :(得分:6)

Requests:您无需显式调用close()。请求完成后将自动关闭,因为它基于urlopen(这就是resp.raw.closed为True的原因),这是我看着session.pyadapters.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(...))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将关闭。

编辑: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