Skip to content

Commit

Permalink
Add custom WSGIMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
RobbeSneyders committed Dec 26, 2022
1 parent 5a0c292 commit 0add539
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
14 changes: 7 additions & 7 deletions connexion/apps/flask_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions connexion/middleware/wsgi.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 0add539

Please sign in to comment.