当前位置: 首页>>代码示例>>Python>>正文


Python settings.MIDDLEWARE_CLASSES属性代码示例

本文整理汇总了Python中django.conf.settings.MIDDLEWARE_CLASSES属性的典型用法代码示例。如果您正苦于以下问题:Python settings.MIDDLEWARE_CLASSES属性的具体用法?Python settings.MIDDLEWARE_CLASSES怎么用?Python settings.MIDDLEWARE_CLASSES使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在django.conf.settings的用法示例。


在下文中一共展示了settings.MIDDLEWARE_CLASSES属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_install_middleware_old_style

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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",
            ]
        ) 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:24,代码来源:test_django.py

示例2: test_old_style_on_response_response_middleware

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:20,代码来源:test_django.py

示例3: test_old_style_on_view_response_middleware

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:26,代码来源:test_django.py

示例4: test_old_style_on_exception_response_middleware

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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" 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:27,代码来源:test_django.py

示例5: test_old_style_exception_on_request_middleware

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:19,代码来源:test_django.py

示例6: get_user

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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() 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:31,代码来源:__init__.py

示例7: clean_url

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:17,代码来源:forms.py

示例8: _session_middleware

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
def _session_middleware():
    return ("django.contrib.sessions.middleware.SessionMiddleware" in
            settings.MIDDLEWARE_CLASSES) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:5,代码来源:sessions.py

示例9: load_middleware

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:40,代码来源:base.py

示例10: load_middleware_wrapper

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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) 
开发者ID:instana,项目名称:python-sensor,代码行数:42,代码来源:middleware.py

示例11: test_user_info_with_non_django_auth

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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"] == {} 
开发者ID:elastic,项目名称:apm-agent-python,代码行数:16,代码来源:django_tests.py

示例12: test_user_info_with_non_django_auth_django_2

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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"] == {} 
开发者ID:elastic,项目名称:apm-agent-python,代码行数:15,代码来源:django_tests.py

示例13: test_user_info_without_auth_middleware

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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"] == {} 
开发者ID:elastic,项目名称:apm-agent-python,代码行数:13,代码来源:django_tests.py

示例14: test_user_info_without_auth_middleware_django_2

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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"] == {} 
开发者ID:elastic,项目名称:apm-agent-python,代码行数:12,代码来源:django_tests.py

示例15: test_middleware_not_set

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import MIDDLEWARE_CLASSES [as 别名]
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 
开发者ID:elastic,项目名称:apm-agent-python,代码行数:12,代码来源:django_tests.py


注:本文中的django.conf.settings.MIDDLEWARE_CLASSES属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。