我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.MIDDLEWARE_CLASSES。
def async_legacy_get_response_dj_1_10(self, request): """ Apply process_request() middleware and call the main _get_response(), if needed. Used only for legacy MIDDLEWARE_CLASSES. """ response = None # Apply request middleware for middleware_method in self._request_middleware: response = middleware_method(request) if isawaitable(response): response = await response if response: break if response is None: response = await self._get_response_inner_dj_1_10(request) return response # This function is protected under the Django BSD 3-Clause licence # This function is reproduced under the terms of the Django Licence # See DJANGO_LICENCE in this source code repository
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 ( (settings.MIDDLEWARE and 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE) or '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
def test_autopatching_twice_middleware(self): ok_(django._datadog_patch) # Call django.setup() twice and ensure we don't add a duplicate tracer django.setup() found_app = settings.INSTALLED_APPS.count('ddtrace.contrib.django') eq_(found_app, 1) eq_(settings.MIDDLEWARE[0], 'ddtrace.contrib.django.TraceMiddleware') ok_('ddtrace.contrib.django.TraceMiddleware' not in settings.MIDDLEWARE_CLASSES) eq_(settings.MIDDLEWARE[-1], 'ddtrace.contrib.django.TraceExceptionMiddleware') ok_('ddtrace.contrib.django.TraceExceptionMiddleware' not in settings.MIDDLEWARE_CLASSES) found_mw = settings.MIDDLEWARE.count('ddtrace.contrib.django.TraceMiddleware') eq_(found_mw, 1) found_mw = settings.MIDDLEWARE.count('ddtrace.contrib.django.TraceExceptionMiddleware') eq_(found_mw, 1)
def check_middlewares(output): with output.section("Middlewares") as section: required_middlewares = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ) for middleware in required_middlewares: if middleware not in settings.MIDDLEWARE_CLASSES: section.error("%s middleware must be in MIDDLEWARE_CLASSES" % middleware)
def check_middleware_installed(app_configs=None, **kwargs): "Ensure that _our_ middleware is installed." from django.conf import settings if getattr(settings, 'MIDDLEWARE', None): MIDDLEWARE_CLASSES = settings.MIDDLEWARE else: MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES errors = [] if MIDDLEWARE not in MIDDLEWARE_CLASSES: errors.append(Error( 'Missing required middleware', hint="Add '{0}' to settings.MIDDLEWARE_CLASSES".format(MIDDLEWARE), id='boardinghouse.E003' )) return errors
def test_form_submission_without_sessions(self): """ Test that a (normal, non-Crispy) form submission results in an additional Sample instance. """ # Disable session MW MW = list(settings.MIDDLEWARE_CLASSES) MW.remove('django.contrib.sessions.middleware.SessionMiddleware') with override_settings(MiddleWare=MW): # First get the number Sample-instances current_samples = Sample.objects.count() sample_name = self.get_random_string(10) sample_msg = self.get_random_string(100) action_url = reverse( 'cmsplugin_form_handler:process_form', args=(self.model_form_plugin.pk, ) ) response = self.client.post(action_url, { 'name': sample_name, 'message': sample_msg, 'cmsplugin_form_source_url': '/en/', }, follow=True) self.assertEqual(response.status_code, 200) assert Sample.objects.count() > current_samples
def _session_middleware(): return ("django.contrib.sessions.middleware.SessionMiddleware" in settings.MIDDLEWARE_CLASSES)
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
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()
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
def _csrf_middleware(): return ("django.middleware.csrf.CsrfViewMiddleware" in settings.MIDDLEWARE_CLASSES or settings.MIDDLEWARE and "django.middleware.csrf.CsrfViewMiddleware" in settings.MIDDLEWARE)
def _session_middleware(): return ("django.contrib.sessions.middleware.SessionMiddleware" in settings.MIDDLEWARE_CLASSES or settings.MIDDLEWARE and "django.contrib.sessions.middleware.SessionMiddleware" in settings.MIDDLEWARE)
def _security_middleware(): return ("django.middleware.security.SecurityMiddleware" in settings.MIDDLEWARE_CLASSES or settings.MIDDLEWARE and "django.middleware.security.SecurityMiddleware" in settings.MIDDLEWARE)
def _xframe_middleware(): return ("django.middleware.clickjacking.XFrameOptionsMiddleware" in settings.MIDDLEWARE_CLASSES or settings.MIDDLEWARE and "django.middleware.clickjacking.XFrameOptionsMiddleware" in settings.MIDDLEWARE)
def check_duplicate_middleware_settings(app_configs, **kwargs): if settings.MIDDLEWARE is not None and settings.MIDDLEWARE_CLASSES != global_settings.MIDDLEWARE_CLASSES: return [Warning( "The MIDDLEWARE_CLASSES setting is deprecated in Django 1.10 " "and the MIDDLEWARE setting takes precedence. Since you've set " "MIDDLEWARE, the value of MIDDLEWARE_CLASSES is ignored.", id='1_10.W001', )] return []
def _legacy_get_response(self, request): """ Apply process_request() middleware and call the main _get_response(), if needed. Used only for legacy MIDDLEWARE_CLASSES. """ response = None # Apply request middleware for middleware_method in self._request_middleware: response = middleware_method(request) if response: break if response is None: response = self._get_response(request) return response
def __init__(self, *args, **kwargs): # `NoCacheMiddlware` depends on `request.sso_user`, which comes from # `SSOUserMiddleware assert ( 'sso.middleware.SSOUserMiddleware' in settings.MIDDLEWARE_CLASSES ) super().__init__(*args, **kwargs)
def test_autopatching_middleware_classes(self): ok_(django._datadog_patch) ok_('ddtrace.contrib.django' in settings.INSTALLED_APPS) eq_(settings.MIDDLEWARE_CLASSES[0], 'ddtrace.contrib.django.TraceMiddleware') eq_(settings.MIDDLEWARE_CLASSES[-1], 'ddtrace.contrib.django.TraceExceptionMiddleware')
def test_autopatching_twice_middleware_classes(self): ok_(django._datadog_patch) # Call django.setup() twice and ensure we don't add a duplicate tracer django.setup() found_app = settings.INSTALLED_APPS.count('ddtrace.contrib.django') eq_(found_app, 1) eq_(settings.MIDDLEWARE_CLASSES[0], 'ddtrace.contrib.django.TraceMiddleware') eq_(settings.MIDDLEWARE_CLASSES[-1], 'ddtrace.contrib.django.TraceExceptionMiddleware') found_mw = settings.MIDDLEWARE_CLASSES.count('ddtrace.contrib.django.TraceMiddleware') eq_(found_mw, 1) found_mw = settings.MIDDLEWARE_CLASSES.count('ddtrace.contrib.django.TraceExceptionMiddleware') eq_(found_mw, 1)
def test_autopatching_middleware(self): ok_(django._datadog_patch) ok_('ddtrace.contrib.django' in settings.INSTALLED_APPS) eq_(settings.MIDDLEWARE[0], 'ddtrace.contrib.django.TraceMiddleware') ok_('ddtrace.contrib.django.TraceMiddleware' not in settings.MIDDLEWARE_CLASSES) eq_(settings.MIDDLEWARE[-1], 'ddtrace.contrib.django.TraceExceptionMiddleware') ok_('ddtrace.contrib.django.TraceExceptionMiddleware' not in settings.MIDDLEWARE_CLASSES)
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) == 1 event = django_elasticapm_client.events.pop(0)['errors'][0] assert event['context']['user'] == {}
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) == 1 event = django_elasticapm_client.events.pop(0)['errors'][0] assert event['context']['user'] == {}
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) == 1 event = django_elasticapm_client.events.pop(0)['errors'][0] assert event['context']['user'] == {}
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) == 1 event = django_elasticapm_client.events.pop(0)['errors'][0] assert event['context']['user'] == {}