當前位置: 首頁>>代碼示例>>Python>>正文


Python settings.MIDDLEWARE屬性代碼示例

本文整理匯總了Python中django.conf.settings.MIDDLEWARE屬性的典型用法代碼示例。如果您正苦於以下問題:Python settings.MIDDLEWARE屬性的具體用法?Python settings.MIDDLEWARE怎麽用?Python settings.MIDDLEWARE使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在django.conf.settings的用法示例。


在下文中一共展示了settings.MIDDLEWARE屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: check

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:24,代碼來源:models.py

示例2: _get_token

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:24,代碼來源:csrf.py

示例3: check_middleware

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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) 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:19,代碼來源:utils.py

示例4: check_crequest

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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 
開發者ID:ra-systems,項目名稱:django-ra-erp,代碼行數:21,代碼來源:checks.py

示例5: test_install_middleware_new_style

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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",
            ]
        ) 
開發者ID:scoutapp,項目名稱:scout_apm_python,代碼行數:24,代碼來源:test_django.py

示例6: __call__

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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 
開發者ID:project-koku,項目名稱:koku,代碼行數:30,代碼來源:iam_test_case.py

示例7: __init__

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:8,代碼來源:session.py

示例8: process_request

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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)) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:10,代碼來源:middleware.py

示例9: clean_url

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:17,代碼來源:forms.py

示例10: check_middleware

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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)) 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:7,代碼來源:utils.py

示例11: load_middleware_wrapper

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [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

示例12: ready

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [as 別名]
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 
開發者ID:jeeyshe,項目名稱:ishare,代碼行數:16,代碼來源:apps.py

示例13: test_user_info_with_non_django_auth_django_2

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [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

示例14: test_user_info_without_auth_middleware_django_2

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MIDDLEWARE [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 [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屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。