本文整理匯總了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
示例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
示例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)
示例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
示例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",
]
)
示例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
示例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)
示例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))
示例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
示例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))
示例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)
示例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
示例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"] == {}
示例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"] == {}
示例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