python-3.xpython-asyncioaiohttp

What does "Cannot write to closing transport" mean?


I get the exception "Cannot write to closing transport" raised from aiohttp.http_writer.StreamWriter#_write, but only in a fraction of cases.

The relevant snippet.

    session: aiohttp.ClientSession
    async with session.get(url, timeout=60) as response:
        txt = await response.text()
        response.close()
        return txt

What is going on? I don't think the server-size is closing the socket.


Solution

  • Answer: We should create a new session on each request. There is also no need to close the response() explicitly, as the context manager handles that.

    async with aiohttp.ClientSession().get(url, timeout=60) as response:
        txt = await response.text()
        return txt