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

Preserve execution context when running code in ThreadPool #191

Closed
tomchristie opened this issue Nov 7, 2018 · 0 comments
Closed

Preserve execution context when running code in ThreadPool #191

tomchristie opened this issue Nov 7, 2018 · 0 comments

Comments

@tomchristie
Copy link
Member

tomchristie commented Nov 7, 2018

See https://github.com/encode/sentry-asgi and getsentry/sentry-python#162 (comment)

We should switch our threadpool code around so that on Python 3.7+ it always runs in the same contextvars context.

We probably want reusable utility function that looks like this:

try:
    import contextvars  # Python 3.7+ only.
except ImportError:
    contextvars = None


async def run_in_threadpool(func, *args, **kwargs):
    loop = asyncio.get_event_loop()
    if contextvars is not None:
        # Ensure we run in the same context
        context = contextvars.copy_context()
        func = functools.partial(context.run, *args, **kwargs)
        args = []
    elif kwargs:
        # loop.run_in_executor doesn't accept 'kwargs', so bind them in here
        func = functools.partial(func, **kwargs)
    return await loop.run_in_executor(None, func, *args)

We should also propose the same for Responder. (I don't think that Quart supports sync views, so it's less of an issue there)

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

1 participant