Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TornadoSession as a context manager #18

Open
Morreski opened this issue Apr 7, 2016 · 3 comments
Open

TornadoSession as a context manager #18

Morreski opened this issue Apr 7, 2016 · 3 comments

Comments

@Morreski
Copy link

Morreski commented Apr 7, 2016

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 !

@gmr
Copy link
Owner

gmr commented Apr 7, 2016

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

@gmr gmr added the bug label Apr 7, 2016
@gmr
Copy link
Owner

gmr commented Oct 27, 2016

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 gmr added enhancement and removed bug labels Feb 21, 2018
@nvllsvm
Copy link
Contributor

nvllsvm commented Aug 7, 2018

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants