From 81464b61074d63d1fa02ee26fa90700516ba3834 Mon Sep 17 00:00:00 2001 From: Robbe Sneyders Date: Fri, 23 Dec 2022 20:23:16 +0100 Subject: [PATCH 1/2] Pass contextvars to threadpool executor --- a2wsgi/wsgi.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/a2wsgi/wsgi.py b/a2wsgi/wsgi.py index 3f3e18a..861ae1c 100644 --- a/a2wsgi/wsgi.py +++ b/a2wsgi/wsgi.py @@ -1,5 +1,6 @@ import asyncio import collections +import functools import os import sys import typing @@ -7,6 +8,12 @@ from .types import Environ, Message, Receive, Scope, Send, StartResponse, WSGIApp +try: + # Python 3.7+ + import contextvars +except ImportError: + contextvars = None + class Body: def __init__(self, loop: asyncio.AbstractEventLoop, receive: Receive) -> None: @@ -184,8 +191,13 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: sender = None try: sender = self.loop.create_task(self.sender(send)) + if contextvars is not None: + context = contextvars.copy_context() + func = functools.partial(context.run, self.wsgi) + else: + func = self.wsgi await self.loop.run_in_executor( - self.executor, self.wsgi, environ, self.start_response + self.executor, func, environ, self.start_response ) self.send_queue.append(None) self.send_event.set() From 36bcb7f947ae990214f18bcde3f3377f8e404ad5 Mon Sep 17 00:00:00 2001 From: Robbe Sneyders Date: Mon, 26 Dec 2022 10:58:32 +0100 Subject: [PATCH 2/2] Remove 3.6 fallback --- a2wsgi/wsgi.py | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/a2wsgi/wsgi.py b/a2wsgi/wsgi.py index 861ae1c..b68adaf 100644 --- a/a2wsgi/wsgi.py +++ b/a2wsgi/wsgi.py @@ -1,5 +1,6 @@ import asyncio import collections +import contextvars import functools import os import sys @@ -8,12 +9,6 @@ from .types import Environ, Message, Receive, Scope, Send, StartResponse, WSGIApp -try: - # Python 3.7+ - import contextvars -except ImportError: - contextvars = None - class Body: def __init__(self, loop: asyncio.AbstractEventLoop, receive: Receive) -> None: @@ -191,11 +186,8 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: sender = None try: sender = self.loop.create_task(self.sender(send)) - if contextvars is not None: - context = contextvars.copy_context() - func = functools.partial(context.run, self.wsgi) - else: - func = self.wsgi + context = contextvars.copy_context() + func = functools.partial(context.run, self.wsgi) await self.loop.run_in_executor( self.executor, func, environ, self.start_response )