Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 217
1111moritz Avatar asked Jan 20 '26 17:01

1111moritz


1 Answers

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.

like image 173
TJR Avatar answered Jan 23 '26 06:01

TJR