Python django.conf.settings.MIDDLEWARE Examples

The following are 30 code examples for showing how to use django.conf.settings.MIDDLEWARE(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def check(cls, **kwargs):
        """
        We use .session_key and CSRF_COOKIE above: check that they will be there, and fail fast if not.
        """
        errors = super().check(**kwargs)

        # Ensure we are using the database session store. (Other SessionStores may also have .session_key?)
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore
        if not issubclass(store, DatabaseSessionStore):
            errors.append(Error(
                "Quiz logging uses request.session.session_key, which likely implies "
                "SESSION_ENGINE = 'django.contrib.sessions.backends.db' in settings."
            ))

        if 'django.middleware.csrf.CsrfViewMiddleware' not in settings.MIDDLEWARE:
            errors.append(Error(
                "CsrfViewMiddleware is not enabled in settings: quiz logging uses CSRF_COOKIE and will fail without "
                "CSRF checking enabled. Also it should be enabled in general."
            ))

        return errors 
Example 2
Project: bioforum   Author: reBiocoder   File: csrf.py    License: MIT License 6 votes vote down vote up
def _get_token(self, request):
        if settings.CSRF_USE_SESSIONS:
            try:
                return request.session.get(CSRF_SESSION_KEY)
            except AttributeError:
                raise ImproperlyConfigured(
                    'CSRF_USE_SESSIONS is enabled, but request.session is not '
                    'set. SessionMiddleware must appear before CsrfViewMiddleware '
                    'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '')
                )
        else:
            try:
                cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                return None

            csrf_token = _sanitize_token(cookie_token)
            if csrf_token != cookie_token:
                # Cookie token needed to be replaced;
                # the cookie needs to be reset.
                request.csrf_cookie_needs_reset = True
            return csrf_token 
Example 3
Project: django-polaris   Author: stellar   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def check_middleware():
    """
    Ensures the Django app running Polaris has the correct middleware
    configuration. Polaris requires SessionMiddleware and
    PolarisSameSiteMiddleware to be installed.
    """
    err_msg = "{} is not installed in settings.MIDDLEWARE"
    session_middleware_path = "django.contrib.sessions.middleware.SessionMiddleware"
    if import_path not in django_settings.MIDDLEWARE:
        raise ValueError(err_msg.format(import_path))
    elif session_middleware_path not in django_settings.MIDDLEWARE:
        raise ValueError(err_msg.format(session_middleware_path))
    elif django_settings.MIDDLEWARE.index(
        import_path
    ) > django_settings.MIDDLEWARE.index(session_middleware_path):
        err_msg = f"{import_path} must be listed before {session_middleware_path}"
        raise ValueError(err_msg) 
Example 4
Project: django-ra-erp   Author: ra-systems   File: checks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def check_crequest(app_configs=None, **kwargs):
    errors = []
    if 'crequest' not in settings.INSTALLED_APPS:
        errors.append(
            Error('crequest app is missing',
                  hint='Add `crequest` to INSTALLED_APPS',
                  obj='settings',
                  id='ra.E003',
                  )
        )
    if 'crequest.middleware.CrequestMiddleware' not in settings.MIDDLEWARE:
        errors.append(
            Error('crequest middleware is missing',
                  hint='Add "crequest.middleware.CrequestMiddleware" to MIDDLEWARE',
                  obj='settings',
                  id='ra.E003',
                  )
        )
    return errors 
Example 5
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: csrf.py    License: MIT License 6 votes vote down vote up
def _get_token(self, request):
        if settings.CSRF_USE_SESSIONS:
            try:
                return request.session.get(CSRF_SESSION_KEY)
            except AttributeError:
                raise ImproperlyConfigured(
                    'CSRF_USE_SESSIONS is enabled, but request.session is not '
                    'set. SessionMiddleware must appear before CsrfViewMiddleware '
                    'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '')
                )
        else:
            try:
                cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                return None

            csrf_token = _sanitize_token(cookie_token)
            if csrf_token != cookie_token:
                # Cookie token needed to be replaced;
                # the cookie needs to be reset.
                request.csrf_cookie_needs_reset = True
            return csrf_token 
Example 6
Project: python   Author: Yeah-Kun   File: csrf.py    License: Apache License 2.0 6 votes vote down vote up
def _get_token(self, request):
        if settings.CSRF_USE_SESSIONS:
            try:
                return request.session.get(CSRF_SESSION_KEY)
            except AttributeError:
                raise ImproperlyConfigured(
                    'CSRF_USE_SESSIONS is enabled, but request.session is not '
                    'set. SessionMiddleware must appear before CsrfViewMiddleware '
                    'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '')
                )
        else:
            try:
                cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                return None

            csrf_token = _sanitize_token(cookie_token)
            if csrf_token != cookie_token:
                # Cookie token needed to be replaced;
                # the cookie needs to be reset.
                request.csrf_cookie_needs_reset = True
            return csrf_token 
Example 7
Project: python2017   Author: bpgc-cte   File: csrf.py    License: MIT License 6 votes vote down vote up
def _get_token(self, request):
        if settings.CSRF_USE_SESSIONS:
            try:
                return request.session.get(CSRF_SESSION_KEY)
            except AttributeError:
                raise ImproperlyConfigured(
                    'CSRF_USE_SESSIONS is enabled, but request.session is not '
                    'set. SessionMiddleware must appear before CsrfViewMiddleware '
                    'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '')
                )
        else:
            try:
                cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                return None

            csrf_token = _sanitize_token(cookie_token)
            if csrf_token != cookie_token:
                # Cookie token needed to be replaced;
                # the cookie needs to be reset.
                request.csrf_cookie_needs_reset = True
            return csrf_token 
Example 8
Project: scout_apm_python   Author: scoutapp   File: test_django.py    License: MIT License 6 votes vote down vote up
def test_install_middleware_new_style(list_or_tuple, preinstalled):
    if preinstalled:
        middleware = list_or_tuple(
            [
                "scout_apm.django.middleware.MiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.ViewTimingMiddleware",
            ]
        )
    else:
        middleware = list_or_tuple(["django.middleware.common.CommonMiddleware"])

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

        assert settings.MIDDLEWARE == list_or_tuple(
            [
                "scout_apm.django.middleware.MiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.ViewTimingMiddleware",
            ]
        ) 
Example 9
Project: koku   Author: project-koku   File: iam_test_case.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, function):
        """Call method."""

        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            user = self.user
            user["access"] = self.access

            dev_middleware = "koku.dev_middleware.DevelopmentIdentityHeaderMiddleware"
            middleware = settings.MIDDLEWARE
            if dev_middleware not in middleware:
                middleware.insert(5, dev_middleware)

            identity = {
                "identity": {"account_number": "10001", "type": "User", "user": user},
                "entitlements": {"cost_management": {"is_entitled": "True"}},
            }

            with override_settings(DEVELOPMENT=True):
                with override_settings(DEVELOPMENT_IDENTITY=identity):
                    with override_settings(MIDDLEWARE=middleware):
                        request_context = IamTestCase._create_request_context(self.customer, user)
                        middleware = DevelopmentIdentityHeaderMiddleware()
                        middleware.process_request(request_context["request"])
                        result = function(*args, **kwargs)
            return result

        return wrapper 
Example 10
Project: bioforum   Author: reBiocoder   File: session.py    License: MIT License 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        assert hasattr(request, 'session'), "The session-based temporary "\
            "message storage requires session middleware to be installed, "\
            "and come before the message middleware in the "\
            "MIDDLEWARE%s list." % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        super().__init__(request, *args, **kwargs) 
Example 11
Project: bioforum   Author: reBiocoder   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        request.user = SimpleLazyObject(lambda: get_user(request)) 
Example 12
Project: bioforum   Author: reBiocoder   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Django remote user auth middleware requires the"
                " authentication middleware to be installed.  Edit your"
                " MIDDLEWARE setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the RemoteUserMiddleware class.")
        try:
            username = request.META[self.header]
        except KeyError:
            # If specified header doesn't exist then remove any existing
            # authenticated remote-user, or return (leaving request.user set to
            # AnonymousUser by the AuthenticationMiddleware).
            if self.force_logout_if_no_header and request.user.is_authenticated:
                self._remove_invalid_user(request)
            return
        # If the user is already authenticated and that user is the user we are
        # getting passed in the headers, then the correct user is already
        # persisted in the session and we don't need to continue.
        if request.user.is_authenticated:
            if request.user.get_username() == self.clean_username(username, request):
                return
            else:
                # An authenticated user is associated with the request, but
                # it does not match the authorized user in the header.
                self._remove_invalid_user(request)

        # We are seeing this user for the first time in this session, attempt
        # to authenticate the user.
        user = auth.authenticate(request, remote_user=username)
        if user:
            # User is valid.  Set request.user and persist user in the session
            # by logging the user in.
            request.user = user
            auth.login(request, user) 
Example 13
Project: bioforum   Author: reBiocoder   File: forms.py    License: MIT License 5 votes vote down vote up
def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                gettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )
        if (settings.APPEND_SLASH and
                'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE and
                not url.endswith('/')):
            raise forms.ValidationError(
                gettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url 
Example 14
Project: django-polaris   Author: stellar   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def check_middleware():
    err_msg = "{} is not installed in settings.MIDDLEWARE"
    cors_middleware_path = "corsheaders.middleware.CorsMiddleware"
    if cors_middleware_path not in django_settings.MIDDLEWARE:
        raise ValueError(err_msg.format(cors_middleware_path)) 
Example 15
Project: python-sensor   Author: instana   File: middleware.py    License: 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 16
Project: ishare   Author: jeeyshe   File: apps.py    License: MIT License 5 votes vote down vote up
def ready(self):
        # 如果是django3+ 就使用中间件,删除header中的X-Frame-Options

        try:
            import django
            version = django.get_version()
            if int(version.split('.')[0]) >= 3:
                from django.conf import settings
                mname = 'simpleui.middlewares.SimpleMiddleware'
                if mname not in settings.MIDDLEWARE:
                    settings.MIDDLEWARE.append(mname)
        except Exception as e:
            pass
        pass 
Example 17
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: session.py    License: MIT License 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        assert hasattr(request, 'session'), "The session-based temporary "\
            "message storage requires session middleware to be installed, "\
            "and come before the message middleware in the "\
            "MIDDLEWARE%s list." % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        super().__init__(request, *args, **kwargs) 
Example 18
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        request.user = SimpleLazyObject(lambda: get_user(request)) 
Example 19
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Django remote user auth middleware requires the"
                " authentication middleware to be installed.  Edit your"
                " MIDDLEWARE setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the RemoteUserMiddleware class.")
        try:
            username = request.META[self.header]
        except KeyError:
            # If specified header doesn't exist then remove any existing
            # authenticated remote-user, or return (leaving request.user set to
            # AnonymousUser by the AuthenticationMiddleware).
            if self.force_logout_if_no_header and request.user.is_authenticated:
                self._remove_invalid_user(request)
            return
        # If the user is already authenticated and that user is the user we are
        # getting passed in the headers, then the correct user is already
        # persisted in the session and we don't need to continue.
        if request.user.is_authenticated:
            if request.user.get_username() == self.clean_username(username, request):
                return
            else:
                # An authenticated user is associated with the request, but
                # it does not match the authorized user in the header.
                self._remove_invalid_user(request)

        # We are seeing this user for the first time in this session, attempt
        # to authenticate the user.
        user = auth.authenticate(request, remote_user=username)
        if user:
            # User is valid.  Set request.user and persist user in the session
            # by logging the user in.
            request.user = user
            auth.login(request, user) 
Example 20
Project: apm-agent-python   Author: elastic   File: django_tests.py    License: 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 21
Project: apm-agent-python   Author: elastic   File: django_tests.py    License: 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 22
Project: apm-agent-python   Author: elastic   File: django_tests.py    License: 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 23
Project: apm-agent-python   Author: elastic   File: django_tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_middleware_not_first():
    stdout = compat.StringIO()
    with override_settings(
        **middleware_setting(django.VERSION, ("foo", "elasticapm.contrib.django.middleware.TracingMiddleware"))
    ):
        call_command("elasticapm", "check", stdout=stdout)
    output = stdout.getvalue()
    assert "not at the first position" in output
    if django.VERSION < (1, 10):
        assert "MIDDLEWARE_CLASSES" in output
    else:
        assert "MIDDLEWARE setting" in output 
Example 24
Project: apm-agent-python   Author: elastic   File: django_tests.py    License: 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 25
Project: python2017   Author: bpgc-cte   File: session.py    License: MIT License 5 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        assert hasattr(request, 'session'), "The session-based temporary "\
            "message storage requires session middleware to be installed, "\
            "and come before the message middleware in the "\
            "MIDDLEWARE%s list." % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        super(SessionStorage, self).__init__(request, *args, **kwargs) 
Example 26
Project: python2017   Author: bpgc-cte   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
        request.user = SimpleLazyObject(lambda: get_user(request)) 
Example 27
Project: python2017   Author: bpgc-cte   File: middleware.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Django remote user auth middleware requires the"
                " authentication middleware to be installed.  Edit your"
                " MIDDLEWARE setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the RemoteUserMiddleware class.")
        try:
            username = request.META[self.header]
        except KeyError:
            # If specified header doesn't exist then remove any existing
            # authenticated remote-user, or return (leaving request.user set to
            # AnonymousUser by the AuthenticationMiddleware).
            if self.force_logout_if_no_header and request.user.is_authenticated:
                self._remove_invalid_user(request)
            return
        # If the user is already authenticated and that user is the user we are
        # getting passed in the headers, then the correct user is already
        # persisted in the session and we don't need to continue.
        if request.user.is_authenticated:
            if request.user.get_username() == self.clean_username(username, request):
                return
            else:
                # An authenticated user is associated with the request, but
                # it does not match the authorized user in the header.
                self._remove_invalid_user(request)

        # We are seeing this user for the first time in this session, attempt
        # to authenticate the user.
        user = auth.authenticate(request, remote_user=username)
        if user:
            # User is valid.  Set request.user and persist user in the session
            # by logging the user in.
            request.user = user
            auth.login(request, user) 
Example 28
Project: scout_apm_python   Author: scoutapp   File: test_django.py    License: MIT License 5 votes vote down vote up
def test_username(tracked_requests):
    new_middleware = (
        settings.MIDDLEWARE[:-1]
        + [__name__ + ".fake_authentication_middleware"]
        + settings.MIDDLEWARE[-1:]
    )
    with app_with_scout(MIDDLEWARE=new_middleware) as app:
        response = TestApp(app).get("/hello/")

    assert response.status_int == 200
    assert len(tracked_requests) == 1
    tracked_request = tracked_requests[0]
    assert tracked_request.tags["username"] == "scout" 
Example 29
Project: scout_apm_python   Author: scoutapp   File: test_django.py    License: MIT License 5 votes vote down vote up
def test_username_exception(tracked_requests):
    new_middleware = (
        settings.MIDDLEWARE[:-1]
        + [__name__ + ".crashy_authentication_middleware"]
        + settings.MIDDLEWARE[-1:]
    )
    with app_with_scout(MIDDLEWARE=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 30
Project: scout_apm_python   Author: scoutapp   File: test_django.py    License: MIT License 5 votes vote down vote up
def test_urlconf(tracked_requests):
    new_middleware = (
        settings.MIDDLEWARE[:-1]
        + [__name__ + ".urlconf_middleware"]
        + settings.MIDDLEWARE[-1:]
    )
    with app_with_scout(MIDDLEWARE=new_middleware) as app:
        response = TestApp(app).get("/hello/")

    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"