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