aiohttp / 从上下文管理器中获取响应对象

aiohttp / Getting response object out of context manager

我目前正在使用 aiohttp(来自 requests 模块)进行我的第一个“婴儿步骤”。

我尝试稍微简化请求,这样我就不必在主模块中为每个请求使用上下文管理器。

因此我尝试了这个:

async def get(session, url, headers, proxies=None):
  async with session.get(url, headers=headers, proxy=proxies) as response:
       response_object = response
  return response_object

但结果是:

<class 'aiohttp.client_exceptions.ClientConnectionError'> - Connection closed 

请求在上下文管理器中可用。当我尝试在上述函数的上下文管理器中访问它时,一切正常。
但是它不应该也能够保存在变量 <response_object> 中然后在之后返回以便我可以在上下文管理器之外访问它吗?
有什么解决方法吗?

如果您不关心在 get 方法中加载的数据,也许您可​​以尝试将其加载到其中:

async def get(session, url, headers, proxies=None):
      async with session.get(url, headers=headers, proxy=proxies) as response:
          await response.read()
      return response

并且使用被阅读的正文:

resp = get(session, 'http://python.org', {})
print(await resp.text())

在幕后,read 方法将正文缓存在名为 _body 的成员中,当尝试调用 json 时,aiohttp 首先检查正文是否已被读取.