1111moritz
1111moritz

Reputation: 156

aiohttp / Getting response object out of context manager

I'm currently doing my first "baby-steps" with aiohttp (coming from the requests module).

I tried to simplify the requests a bit so I wont have to use a context manager for each request in my main module.

Therefore I tried this:

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

But it resulted in:

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

The request is available in the context manager. When I try to access it within the context manager in the mentioned function, all works.
But shouldn't it also be able to be saved in the variable <response_object> and then be returned afterwards so I can access it outside of the context manager?
Is there any workaround to this?

Upvotes: 3

Views: 2768

Answers (1)

TJR
TJR

Reputation: 484

If you don't care for the data being loaded during the get method, perhaps you could try loading it inside it:

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

And the using the body that was read like:

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

Under the hood, the read method caches the body in a member named _body and when trying to call json, aiohttp first checks whether the body was already read or not.

Upvotes: 4

Related Questions