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

aiohttp leaks ContextVar changes despite ctx = context_copy(); ctx.run() #13

Closed
mistotebe opened this issue Jan 10, 2020 · 3 comments
Closed

Comments

@mistotebe
Copy link

Potentially related to #2.

Take the following code:

#!/usr/bin/env python3

from aiohttp import web
import contextvars
import functools

variable = contextvars.ContextVar('variable')
variable.set(False)


def with_context(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        ctx = contextvars.copy_context()
        return ctx.run(f, *args, **kwargs)
    return wrapper


@with_context
async def handler(request):
    before = variable.get()

    if request.method == 'GET':
        variable.set(True)

    after = variable.get()
    return web.json_response({'before': before, 'after': after})


def main():
    app = web.Application()

    app.router.add_get('/action', handler)
    app.router.add_post('/action', handler)

    web.run_app(app, host='localhost', port=12345)

if __name__ == '__main__':
    main()

In 3.7 contextvars (stdlib implementation), GET requests do not interfere with variable (even if the decorator is not present). In 3.6 with contextvars 2.4, the change to variable leaks out, regardless of whether handler is decorated.

Why does ctx.run() not protect the top-level context from changes?

Is there a workaround?

@1st1
Copy link
Member

1st1 commented Jan 10, 2020

Yeah, this seems to be related to #2. :(

I'll be frank -- there are no plans to further enhance this package. It exists solely for the purpose of defining contextvars APIs for other packages like trio and uvloop. I'd suggest to start using the latest 3.7/3.8 Python instead of relying on this package.

@1st1 1st1 closed this as completed Jan 10, 2020
@mistotebe
Copy link
Author

I was hoping to use this package as a backport of contextvars to 3.6 until we can get rid of RHEL7.

Do you have any ideas what is broken, so I could take a stab at fixing it?

@1st1
Copy link
Member

1st1 commented Jan 14, 2020

Nothing is broken, but the integration with asyncio is missing. And it's a huge one requiring a lot of work.

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

No branches or pull requests

2 participants