python - What's wrong with this async aiohttp code? -


for following code using aiohttp:

async def send(self, msg, url):     async aiohttp.clientsession() session:         async session.post(url, data=msg) response:             self._msg = response.read()  async def recv(self):     return await self._msg 

it works... of time, (frequently, actually) results in various exceptions - truncated responses, or connection being closed exception.

by contrast, following works perfectly:

async def send(self, msg, url):     async aiohttp.clientsession() session:         async session.post(url, data=msg) response:             self._msg = await response.read()  async def recv(self):     return self._msg 

i know why, second version technically incorrect purposes , need fix it. (it incorrect because recv function might called before response has been read)

with context manager, runs code before , after statements within it's block, bookkeeping usually. meaning, first recv function awaits on future references closed connection, or along these lines.

let's have code looks this:

with open(...) file:     file.read() 

this does, roughly:

file = open(...) file.read() file.close() 

and equivalent of you're doing in first example:

file = open() file.close() ... file.read() 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -