Skip to content
Advertisement

Python – getting lost around async

As the title said – I’m having a problem with async stuff. What I’m trying to achieve is written under every function. Sadly in this state of code I’m getting and error:

TypeError: object StreamReader can't be used in 'await' expression and at the end RuntimeError: Event loop is closed

I was googling for a while and didn’t really find a solution for my thing. Is there anyone who can help me a bit and clear what am I doing wrong? Am I allowed to have 2x async with .. in one async function?

Thanks!

JavaScript

Advertisement

Answer

Your issue is the improper use of the resp.content variable below.

JavaScript

See aiohttp’s streaming response content documentation.

While methods read(), json() and text() are very convenient you should use them carefully. All these methods load the whole response in memory. For example if you want to download several gigabyte sized files, these methods will load all the data in memory. Instead you can use the content attribute. It is an instance of the aiohttp.StreamReader class. The gzip and deflate transfer-encodings are automatically decoded for you:

JavaScript

You can either

  • (a) download chunks and store them into disk, or
  • (b) if the binary is not large and can be stored into memory — which seems to be the case based on your use of BytesIO — use io.BytesIO(await resp.read()) (see binary response content.)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement