diff --git a/connexion/apps/flask_app.py b/connexion/apps/flask_app.py index be5a26cb7..7346b8f06 100644 --- a/connexion/apps/flask_app.py +++ b/connexion/apps/flask_app.py @@ -12,12 +12,12 @@ from flask import signals from connexion import jsonifier - -from ..apis.flask_api import FlaskApi -from ..exceptions import ProblemException -from ..middleware import ConnexionMiddleware -from ..problem import problem -from .abstract import AbstractApp +from connexion.apis.flask_api import FlaskApi +from connexion.apps.abstract import AbstractApp +from connexion.exceptions import ProblemException +from connexion.middleware import ConnexionMiddleware +from connexion.middleware.wsgi import WSGIMiddleware +from connexion.problem import problem logger = logging.getLogger("connexion.app") @@ -50,7 +50,7 @@ def create_app(self): return app def _apply_middleware(self, middlewares): - middlewares = [*middlewares, a2wsgi.WSGIMiddleware] + middlewares = [*middlewares, WSGIMiddleware] middleware = ConnexionMiddleware(self.app.wsgi_app, middlewares=middlewares) # Wrap with ASGI to WSGI middleware for usage with development server and test client diff --git a/connexion/middleware/wsgi.py b/connexion/middleware/wsgi.py new file mode 100644 index 000000000..2b98a306f --- /dev/null +++ b/connexion/middleware/wsgi.py @@ -0,0 +1,25 @@ +""" +Module that monkey patches a2wsgi to make contextvars available to the WSGI application. +This can be removed once https://github.com/abersheeran/a2wsgi/pull/31 is merged. +""" +import contextvars +import functools + +import a2wsgi.wsgi +from a2wsgi.wsgi import WSGIResponder + + +class ContextWSGIResponder(WSGIResponder): + """Custom Responder that makes contextvars available to the WSGI application.""" + + @property + def wsgi(self): + context = contextvars.copy_context() + return functools.partial(context.run, super().wsgi) + + +# Monkeypatch module with our custom Responder +a2wsgi.wsgi.WSGIResponder = ContextWSGIResponder + +# Import the WSGIMiddleware now so it uses our custom Responder +from a2wsgi import WSGIMiddleware # NOQA