What's wrong with this async aiohttp code?

Viewed 243

For the following code using aiohttp:

async def send(self, msg, url):
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=msg) as response:
            self._msg = response.read()

async def recv(self):
    return await self._msg

It works... Most of the time, but occasionally (frequently, actually) results in various exceptions - usually truncated responses, or a connection already being closed exception.

By contrast, the following works perfectly:

async def send(self, msg, url):
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=msg) as response:
            self._msg = await response.read()

async def recv(self):
    return self._msg

I would like to know why, as the second version is technically incorrect for my purposes and I need to fix it. (It is incorrect because the recv function might be called before the response has been read)

1 Answers
Related