queries
queries copied to clipboard
TornadoSession as a context manager
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 !
Thanks, I agree, the context manager should free any pending results.
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__.
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)