queries icon indicating copy to clipboard operation
queries copied to clipboard

TornadoSession as a context manager

Open Morreski opened this issue 9 years ago • 3 comments

Hello ! First of all thank you for the work you put in your lib !

We spotted a strange behavior when using queries.TornadoSession in a context manager: The connection pool is not freed when exiting the with block. (This isn't the case for queries.Session).

It is true that the documentation encourages to use result.free() when working with asynchronous sessions but IMHO it would be a nice feature if both Session classes would behave the same.

Cheers !

Morreski avatar Apr 07 '16 14:04 Morreski

Thanks, I agree, the context manager should free any pending results.

gmr avatar Apr 07 '16 23:04 gmr

I investigated this a bit and found it requires some rework, because we don't keep a stack of the results instances. To facilitate this, I'd probably need to keep track of a stack of Result instances that can be iterated and cleaned on __exit__.

gmr avatar Oct 27 '16 14:10 gmr

Using an async context manager with Python 3.7 and Tornado 5.0+ solves this nicely. The async_generator may be used to backport this to as low as Python 3.5.

import contextlib

class AsyncSession(queries.TornadoSession):

    @contextlib.asynccontextmanager
    async def query(self, *args, **kwargs):
        result = await super().query(*args, **kwargs)
        try:
            yield result
        finally:
            result.free()

session = AsyncSession(...)
async with session.query(sql) as result:
    print(result)

nvllsvm avatar Aug 07 '18 21:08 nvllsvm