Python django.conf.settings.MIDDLEWARE_CLASSES Examples

The following are 25 code examples of django.conf.settings.MIDDLEWARE_CLASSES(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: test_django.py    From scout_apm_python with MIT License 6 votes vote down vote up
def test_old_style_exception_on_request_middleware(middleware_index, tracked_requests):
    """
    Test the case that a middleware got added/injected that raises an exception
    in its process_request.
    """
    new_middleware = (
        settings.MIDDLEWARE_CLASSES[:middleware_index]
        + [__name__ + "." + OldStyleExceptionOnRequestMiddleware.__name__]
        + settings.MIDDLEWARE_CLASSES[middleware_index:]
    )
    with app_with_scout(
        MIDDLEWARE_CLASSES=new_middleware, DEBUG_PROPAGATE_EXCEPTIONS=False
    ) as app:
        response = TestApp(app).get("/", expect_errors=True)

    assert response.status_int == 500
    assert len(tracked_requests) == 0 
Example #2
Source File: test_django.py    From scout_apm_python with MIT License 6 votes vote down vote up
def test_old_style_on_exception_response_middleware(middleware_index, tracked_requests):
    """
    Test the case that a middleware got added/injected that generates a
    response in its process_exception. This should follow basically the same
    path as normal view exception, since Django applies process_response from
    middleware on the outgoing response.
    """
    new_middleware = (
        settings.MIDDLEWARE_CLASSES[:middleware_index]
        + [__name__ + "." + OldStyleOnExceptionResponseMiddleware.__name__]
        + settings.MIDDLEWARE_CLASSES[middleware_index:]
    )
    with app_with_scout(MIDDLEWARE_CLASSES=new_middleware) as app:
        response = TestApp(app).get("/crash/")

    assert response.status_int == 200
    assert response.text == "process_exception response!"
    assert len(tracked_requests) == 1

    # In the case that the middleware is added after OldStyleViewMiddleware,
    # its process_exception won't be called so we won't know it's an error.
    # Nothing we can do there - but it's a rare case, since we programatically
    # add our middleware at the end of the stack.
    if middleware_index != 999:
        assert tracked_requests[0].tags["error"] == "true" 
Example #3
Source File: test_django.py    From scout_apm_python with MIT License 6 votes vote down vote up
def test_old_style_on_view_response_middleware(middleware_index, tracked_requests):
    """
    Test the case that a middleware got added/injected that generates a fresh
    response in its process_response. This will count as a real request because
    it reaches the view, but then the view's response gets replaced on the way
    out.
    """
    new_middleware = (
        settings.MIDDLEWARE_CLASSES[:middleware_index]
        + [__name__ + "." + OldStyleOnViewResponseMiddleware.__name__]
        + settings.MIDDLEWARE_CLASSES[middleware_index:]
    )
    with app_with_scout(MIDDLEWARE_CLASSES=new_middleware) as app:
        response = TestApp(app).get("/")

    assert response.status_int == 200
    assert response.text == "process_view response!"
    # If the middleware is before OldStyleViewMiddleware, its process_view
    # won't be called and we won't know to mark the request as real, so it
    # won't be tracked.
    if middleware_index != 999:
        assert len(tracked_requests) == 0
    else:
        assert len(tracked_requests) == 1 
Example #4
Source File: test_django.py    From scout_apm_python with MIT License 6 votes vote down vote up
def test_old_style_on_response_response_middleware(middleware_index, tracked_requests):
    """
    Test the case that a middleware got added/injected that generates a fresh
    response in its process_response. This will count as a real request because
    it reaches the view, but then the view's response gets replaced on the way
    out.
    """
    new_middleware = (
        settings.MIDDLEWARE_CLASSES[:middleware_index]
        + [__name__ + "." + OldStyleOnResponseResponseMiddleware.__name__]
        + settings.MIDDLEWARE_CLASSES[middleware_index:]
    )
    with app_with_scout(MIDDLEWARE_CLASSES=new_middleware) as app:
        response = TestApp(app).get("/")

    assert response.status_int == 200
    assert response.text == "process_response response!"
    assert len(tracked_requests) == 1 
Example #5
Source File: test_django.py    From scout_apm_python with MIT License 6 votes vote down vote up
def test_install_middleware_old_style(list_or_tuple, preinstalled):
    if preinstalled:
        middleware = list_or_tuple(
            [
                "scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.OldStyleViewMiddleware",
            ]
        )
    else:
        middleware = list_or_tuple(["django.middleware.common.CommonMiddleware"])

    with override_settings(MIDDLEWARE_CLASSES=middleware):
        apps.get_app_config("scout_apm").install_middleware()

        assert settings.MIDDLEWARE_CLASSES == list_or_tuple(
            [
                "scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.OldStyleViewMiddleware",
            ]
        ) 
Example #6
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_user(request):
    """
    Returns the user model instance associated with the given request session.
    If no user is retrieved an instance of `AnonymousUser` is returned.
    """
    from .models import AnonymousUser
    user = None
    try:
        user_id = _get_user_session_key(request)
        backend_path = request.session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in settings.AUTHENTICATION_BACKENDS:
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            # Verify the session
            if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware'
                    in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')):
                session_hash = request.session.get(HASH_SESSION_KEY)
                session_hash_verified = session_hash and constant_time_compare(
                    session_hash,
                    user.get_session_auth_hash()
                )
                if not session_hash_verified:
                    request.session.flush()
                    user = None

    return user or AnonymousUser() 
Example #7
Source File: test_views.py    From connect with MIT License 5 votes vote down vote up
def test_get_queryset(self):
        """get_queryset should add the correct extra attributes."""
        # Create a fresh user
        user = User.objects.create_user(
            username='hjkdhds@12ioavoi3.local', password='moo')
        user.add_to_group(self.group1.pk)

        # Create a fresh message and flag it
        thread = mommy.make('connectmessages.Thread', group=self.group1)
        message = mommy.make(
            'connectmessages.Message', sender=user, thread=thread)
        mommy.make('connectmessages.Message', sender=user, thread=thread)
        message.flag(flagged_by=self.staff_user)

        # Authenticate the user so they have a visit count
        middleware = list(settings.MIDDLEWARE_CLASSES)
        if ('open_connect.middleware.visit_tracking.VisitTrackingMiddleware'
                not in middleware):
            middleware.insert(
                0,
                'open_connect.middleware.visit_tracking.'
                'VisitTrackingMiddleware'
                )
        with override_settings(MIDDLEWARE_CLASSES=middleware):
            client = Client()
            client.post(
                reverse('account_login'),
                {'login': 'hjkdhds@12ioavoi3.local', 'password': 'moo'}
            )

        # Get the queryset
        view = UserReportListView()
        view.request = self.request_factory.get('/')
        queryset = view.get_queryset()

        # Make sure everything looks right
        user = queryset.get(pk=user.pk)
        self.assertEqual(user.flags_received, 1)
        self.assertEqual(user.messages_sent, 2)
        self.assertEqual(user.visit_count, 1) 
Example #8
Source File: test_django.py    From scout_apm_python with MIT License 5 votes vote down vote up
def test_old_style_timing_middleware_deleted(url, expected_status, tracked_requests):
    """
    Test the case that some adversarial thing fiddled with the settings
    after app.ready() (like we do!) in order to remove the
    OldStyleMiddlewareTimingMiddleware. The tracked request won't be started
    but OldStyleViewMiddleware defends against this.
    """
    new_middleware = settings.MIDDLEWARE_CLASSES[1:]
    with app_with_scout(
        MIDDLEWARE_CLASSES=new_middleware, DEBUG_PROPAGATE_EXCEPTIONS=False
    ) as app:
        response = TestApp(app).get(url, expect_errors=True)

    assert response.status_int == expected_status
    assert len(tracked_requests) == 0 
Example #9
Source File: test_django.py    From scout_apm_python with MIT License 5 votes vote down vote up
def test_old_style_urlconf(tracked_requests):
    new_middleware = (
        settings.MIDDLEWARE_CLASSES[:-1]
        + [__name__ + ".UrlconfMiddleware"]
        + settings.MIDDLEWARE_CLASSES[-1:]
    )
    with app_with_scout(MIDDLEWARE_CLASSES=new_middleware) as app:
        response = TestApp(app).get("/")

    assert response.status_int == 200
    assert len(tracked_requests) == 1
    tracked_request = tracked_requests[0]
    assert tracked_request.tags["urlconf"] == "tests.integration.django_app_second_copy" 
Example #10
Source File: test_django.py    From scout_apm_python with MIT License 5 votes vote down vote up
def test_old_style_username_exception(tracked_requests):
    new_middleware = (
        settings.MIDDLEWARE_CLASSES[:-1]
        + [__name__ + ".CrashyAuthenticationMiddleware"]
        + settings.MIDDLEWARE_CLASSES[-1:]
    )
    with app_with_scout(MIDDLEWARE_CLASSES=new_middleware) as app:
        response = TestApp(app).get("/")

    assert response.status_int == 200
    assert len(tracked_requests) == 1
    tracked_request = tracked_requests[0]
    assert "username" not in tracked_request.tags 
Example #11
Source File: test_django.py    From scout_apm_python with MIT License 5 votes vote down vote up
def test_old_style_username(tracked_requests):
    new_middleware = (
        settings.MIDDLEWARE_CLASSES[:-1]
        + [__name__ + ".FakeAuthenticationMiddleware"]
        + settings.MIDDLEWARE_CLASSES[-1:]
    )
    with app_with_scout(MIDDLEWARE_CLASSES=new_middleware) as app:
        response = TestApp(app).get("/")

    assert response.status_int == 200
    assert len(tracked_requests) == 1
    tracked_request = tracked_requests[0]
    assert tracked_request.tags["username"] == "scout" 
Example #12
Source File: forms.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                ugettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )
        if (settings.APPEND_SLASH and
                'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES and
                not url.endswith('/')):
            raise forms.ValidationError(
                ugettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url 
Example #13
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_user(request):
    """
    Returns the user model instance associated with the given request session.
    If no user is retrieved an instance of `AnonymousUser` is returned.
    """
    from .models import AnonymousUser
    user = None
    try:
        user_id = _get_user_session_key(request)
        backend_path = request.session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in settings.AUTHENTICATION_BACKENDS:
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            # Verify the session
            if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware'
                    in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')):
                session_hash = request.session.get(HASH_SESSION_KEY)
                session_hash_verified = session_hash and constant_time_compare(
                    session_hash,
                    user.get_session_auth_hash()
                )
                if not session_hash_verified:
                    request.session.flush()
                    user = None

    return user or AnonymousUser() 
Example #14
Source File: django_tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_django_1_10_uses_deprecated_MIDDLEWARE_CLASSES():
    stdout = compat.StringIO()
    with override_settings(
        MIDDLEWARE=None, MIDDLEWARE_CLASSES=["foo", "elasticapm.contrib.django.middleware.TracingMiddleware"]
    ):
        call_command("elasticapm", "check", stdout=stdout)
    output = stdout.getvalue()
    assert "not at the first position" in output 
Example #15
Source File: django_tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_middleware_not_set():
    stdout = compat.StringIO()
    with override_settings(**middleware_setting(django.VERSION, ())):
        call_command("elasticapm", "check", stdout=stdout)
    output = stdout.getvalue()
    assert "Tracing middleware not configured!" in output
    if django.VERSION < (1, 10):
        assert "MIDDLEWARE_CLASSES" in output
    else:
        assert "MIDDLEWARE setting" in output 
Example #16
Source File: django_tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_user_info_without_auth_middleware_django_2(django_elasticapm_client, client):
    with override_settings(
        MIDDLEWARE_CLASSES=None,
        MIDDLEWARE=[m for m in settings.MIDDLEWARE if m != "django.contrib.auth.middleware.AuthenticationMiddleware"],
    ):
        with pytest.raises(Exception):
            client.get(reverse("elasticapm-raise-exc"))
    assert len(django_elasticapm_client.events[ERROR]) == 1
    event = django_elasticapm_client.events[ERROR][0]
    assert event["context"]["user"] == {} 
Example #17
Source File: django_tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_user_info_without_auth_middleware(django_elasticapm_client, client):
    with override_settings(
        MIDDLEWARE_CLASSES=[
            m for m in settings.MIDDLEWARE_CLASSES if m != "django.contrib.auth.middleware.AuthenticationMiddleware"
        ]
    ):
        with pytest.raises(Exception):
            client.get(reverse("elasticapm-raise-exc"))
    assert len(django_elasticapm_client.events[ERROR]) == 1
    event = django_elasticapm_client.events[ERROR][0]
    assert event["context"]["user"] == {} 
Example #18
Source File: django_tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_user_info_with_non_django_auth_django_2(django_elasticapm_client, client):
    with override_settings(
        INSTALLED_APPS=[app for app in settings.INSTALLED_APPS if app != "django.contrib.auth"]
    ) and override_settings(
        MIDDLEWARE_CLASSES=None,
        MIDDLEWARE=[m for m in settings.MIDDLEWARE if m != "django.contrib.auth.middleware.AuthenticationMiddleware"],
    ):
        with pytest.raises(Exception):
            resp = client.get(reverse("elasticapm-raise-exc"))

    assert len(django_elasticapm_client.events[ERROR]) == 1
    event = django_elasticapm_client.events[ERROR][0]
    assert event["context"]["user"] == {} 
Example #19
Source File: django_tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_user_info_with_non_django_auth(django_elasticapm_client, client):
    with override_settings(
        INSTALLED_APPS=[app for app in settings.INSTALLED_APPS if app != "django.contrib.auth"]
    ) and override_settings(
        MIDDLEWARE_CLASSES=[
            m for m in settings.MIDDLEWARE_CLASSES if m != "django.contrib.auth.middleware.AuthenticationMiddleware"
        ]
    ):
        with pytest.raises(Exception):
            resp = client.get(reverse("elasticapm-raise-exc"))

    assert len(django_elasticapm_client.events[ERROR]) == 1
    event = django_elasticapm_client.events[ERROR][0]
    assert event["context"]["user"] == {} 
Example #20
Source File: middleware.py    From python-sensor with MIT License 5 votes vote down vote up
def load_middleware_wrapper(wrapped, instance, args, kwargs):
    try:
        from django.conf import settings

        # Django >=1.10 to <2.0 support old-style MIDDLEWARE_CLASSES so we
        # do as well here
        if hasattr(settings, 'MIDDLEWARE') and settings.MIDDLEWARE is not None:
            if DJ_INSTANA_MIDDLEWARE in settings.MIDDLEWARE:
                return wrapped(*args, **kwargs)

            # Save the list of middleware for Snapshot reporting
            agent.sensor.meter.djmw = settings.MIDDLEWARE

            if type(settings.MIDDLEWARE) is tuple:
                settings.MIDDLEWARE = (DJ_INSTANA_MIDDLEWARE,) + settings.MIDDLEWARE
            elif type(settings.MIDDLEWARE) is list:
                settings.MIDDLEWARE = [DJ_INSTANA_MIDDLEWARE] + settings.MIDDLEWARE
            else:
                logger.warning("Instana: Couldn't add InstanaMiddleware to Django")

        elif hasattr(settings, 'MIDDLEWARE_CLASSES') and settings.MIDDLEWARE_CLASSES is not None:
            if DJ_INSTANA_MIDDLEWARE in settings.MIDDLEWARE_CLASSES:
                return wrapped(*args, **kwargs)

            # Save the list of middleware for Snapshot reporting
            agent.sensor.meter.djmw = settings.MIDDLEWARE_CLASSES

            if type(settings.MIDDLEWARE_CLASSES) is tuple:
                settings.MIDDLEWARE_CLASSES = (DJ_INSTANA_MIDDLEWARE,) + settings.MIDDLEWARE_CLASSES
            elif type(settings.MIDDLEWARE_CLASSES) is list:
                settings.MIDDLEWARE_CLASSES = [DJ_INSTANA_MIDDLEWARE] + settings.MIDDLEWARE_CLASSES
            else:
                logger.warning("Instana: Couldn't add InstanaMiddleware to Django")

        else:
            logger.warning("Instana: Couldn't find middleware settings")

        return wrapped(*args, **kwargs)
    except Exception:
        logger.warning("Instana: Couldn't add InstanaMiddleware to Django: ", exc_info=True) 
Example #21
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def load_middleware(self):
        """
        Populate middleware lists from settings.MIDDLEWARE_CLASSES.

        Must be called after the environment is fixed (see __call__ in subclasses).
        """
        self._view_middleware = []
        self._template_response_middleware = []
        self._response_middleware = []
        self._exception_middleware = []

        request_middleware = []
        for middleware_path in settings.MIDDLEWARE_CLASSES:
            mw_class = import_string(middleware_path)
            try:
                mw_instance = mw_class()
            except MiddlewareNotUsed as exc:
                if settings.DEBUG:
                    if six.text_type(exc):
                        logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
                    else:
                        logger.debug('MiddlewareNotUsed: %r', middleware_path)
                continue

            if hasattr(mw_instance, 'process_request'):
                request_middleware.append(mw_instance.process_request)
            if hasattr(mw_instance, 'process_view'):
                self._view_middleware.append(mw_instance.process_view)
            if hasattr(mw_instance, 'process_template_response'):
                self._template_response_middleware.insert(0, mw_instance.process_template_response)
            if hasattr(mw_instance, 'process_response'):
                self._response_middleware.insert(0, mw_instance.process_response)
            if hasattr(mw_instance, 'process_exception'):
                self._exception_middleware.insert(0, mw_instance.process_exception)

        # We only assign to this when initialization is complete as it is used
        # as a flag for initialization being complete.
        self._request_middleware = request_middleware 
Example #22
Source File: sessions.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _session_middleware():
    return ("django.contrib.sessions.middleware.SessionMiddleware" in
            settings.MIDDLEWARE_CLASSES) 
Example #23
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                ugettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )
        if (settings.APPEND_SLASH and
                'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES and
                not url.endswith('/')):
            raise forms.ValidationError(
                ugettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url 
Example #24
Source File: apps.py    From scout_apm_python with MIT License 4 votes vote down vote up
def install_middleware(self):
        """
        Attempts to insert the ScoutApm middleware as the first middleware
        (first on incoming requests, last on outgoing responses).
        """
        from django.conf import settings

        # If MIDDLEWARE is set, update that, with handling of tuple vs array forms
        if getattr(settings, "MIDDLEWARE", None) is not None:
            timing_middleware = "scout_apm.django.middleware.MiddlewareTimingMiddleware"
            view_middleware = "scout_apm.django.middleware.ViewTimingMiddleware"

            if isinstance(settings.MIDDLEWARE, tuple):
                if timing_middleware not in settings.MIDDLEWARE:
                    settings.MIDDLEWARE = (timing_middleware,) + settings.MIDDLEWARE
                if view_middleware not in settings.MIDDLEWARE:
                    settings.MIDDLEWARE = settings.MIDDLEWARE + (view_middleware,)
            else:
                if timing_middleware not in settings.MIDDLEWARE:
                    settings.MIDDLEWARE.insert(0, timing_middleware)
                if view_middleware not in settings.MIDDLEWARE:
                    settings.MIDDLEWARE.append(view_middleware)

        # Otherwise, we're doing old style middleware, do the same thing with
        # the same handling of tuple vs array forms
        else:
            timing_middleware = (
                "scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware"
            )
            view_middleware = "scout_apm.django.middleware.OldStyleViewMiddleware"

            if isinstance(settings.MIDDLEWARE_CLASSES, tuple):
                if timing_middleware not in settings.MIDDLEWARE_CLASSES:
                    settings.MIDDLEWARE_CLASSES = (
                        timing_middleware,
                    ) + settings.MIDDLEWARE_CLASSES

                if view_middleware not in settings.MIDDLEWARE_CLASSES:
                    settings.MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES + (
                        view_middleware,
                    )
            else:
                if timing_middleware not in settings.MIDDLEWARE_CLASSES:
                    settings.MIDDLEWARE_CLASSES.insert(0, timing_middleware)
                if view_middleware not in settings.MIDDLEWARE_CLASSES:
                    settings.MIDDLEWARE_CLASSES.append(view_middleware) 
Example #25
Source File: base.py    From luscan-devel with GNU General Public License v2.0 4 votes vote down vote up
def load_middleware(self):
        """
        Populate middleware lists from settings.MIDDLEWARE_CLASSES.

        Must be called after the environment is fixed (see __call__ in subclasses).
        """
        self._view_middleware = []
        self._template_response_middleware = []
        self._response_middleware = []
        self._exception_middleware = []

        request_middleware = []
        for middleware_path in settings.MIDDLEWARE_CLASSES:
            try:
                mw_module, mw_classname = middleware_path.rsplit('.', 1)
            except ValueError:
                raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path)
            try:
                mod = import_module(mw_module)
            except ImportError as e:
                raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
            try:
                mw_class = getattr(mod, mw_classname)
            except AttributeError:
                raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname))
            try:
                mw_instance = mw_class()
            except exceptions.MiddlewareNotUsed:
                continue

            if hasattr(mw_instance, 'process_request'):
                request_middleware.append(mw_instance.process_request)
            if hasattr(mw_instance, 'process_view'):
                self._view_middleware.append(mw_instance.process_view)
            if hasattr(mw_instance, 'process_template_response'):
                self._template_response_middleware.insert(0, mw_instance.process_template_response)
            if hasattr(mw_instance, 'process_response'):
                self._response_middleware.insert(0, mw_instance.process_response)
            if hasattr(mw_instance, 'process_exception'):
                self._exception_middleware.insert(0, mw_instance.process_exception)

        # We only assign to this when initialization is complete as it is used
        # as a flag for initialization being complete.
        self._request_middleware = request_middleware