Python django.conf.settings.MIDDLEWARE Examples
The following are 30
code examples of django.conf.settings.MIDDLEWARE().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.conf.settings
, or try the search function
.
Example #1
Source File: csrf.py From bioforum with MIT License | 6 votes |
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
Example #2
Source File: models.py From coursys with GNU General Public License v3.0 | 6 votes |
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
Example #3
Source File: csrf.py From python2017 with MIT License | 6 votes |
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
Example #4
Source File: csrf.py From python with Apache License 2.0 | 6 votes |
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
Example #5
Source File: test_django.py From scout_apm_python with MIT License | 6 votes |
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", ] )
Example #6
Source File: utils.py From django-polaris with Apache License 2.0 | 6 votes |
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)
Example #7
Source File: checks.py From django-ra-erp with GNU Affero General Public License v3.0 | 6 votes |
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
Example #8
Source File: csrf.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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
Example #9
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_django_1_10_uses_deprecated_MIDDLEWARE_CLASSES(): stdout = compat.StringIO() with override_settings( MIDDLEWARE=None, MIDDLEWARE_CLASSES=["foo", "elasticapm.contrib.django.middleware.TracingMiddleware"] ): call_command("elasticapm", "check", stdout=stdout) output = stdout.getvalue() assert "not at the first position" in output
Example #10
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
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"] == {}
Example #11
Source File: session.py From python2017 with MIT License | 5 votes |
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(SessionStorage, self).__init__(request, *args, **kwargs)
Example #12
Source File: middleware.py From python2017 with MIT License | 5 votes |
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))
Example #13
Source File: middleware.py From python2017 with MIT License | 5 votes |
def process_request(self, request): # AuthenticationMiddleware is required so that request.user exists. if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the RemoteUserMiddleware class.") try: username = request.META[self.header] except KeyError: # If specified header doesn't exist then remove any existing # authenticated remote-user, or return (leaving request.user set to # AnonymousUser by the AuthenticationMiddleware). if self.force_logout_if_no_header and request.user.is_authenticated: self._remove_invalid_user(request) return # If the user is already authenticated and that user is the user we are # getting passed in the headers, then the correct user is already # persisted in the session and we don't need to continue. if request.user.is_authenticated: if request.user.get_username() == self.clean_username(username, request): return else: # An authenticated user is associated with the request, but # it does not match the authorized user in the header. self._remove_invalid_user(request) # We are seeing this user for the first time in this session, attempt # to authenticate the user. user = auth.authenticate(request, remote_user=username) if user: # User is valid. Set request.user and persist user in the session # by logging the user in. request.user = user auth.login(request, user)
Example #14
Source File: test_django.py From scout_apm_python with MIT License | 5 votes |
def test_username(tracked_requests): new_middleware = ( settings.MIDDLEWARE[:-1] + [__name__ + ".fake_authentication_middleware"] + settings.MIDDLEWARE[-1:] ) with app_with_scout(MIDDLEWARE=new_middleware) as app: response = TestApp(app).get("/hello/") assert response.status_int == 200 assert len(tracked_requests) == 1 tracked_request = tracked_requests[0] assert tracked_request.tags["username"] == "scout"
Example #15
Source File: test_django.py From scout_apm_python with MIT License | 5 votes |
def test_username_exception(tracked_requests): new_middleware = ( settings.MIDDLEWARE[:-1] + [__name__ + ".crashy_authentication_middleware"] + settings.MIDDLEWARE[-1:] ) with app_with_scout(MIDDLEWARE=new_middleware) as app: response = TestApp(app).get("/") assert response.status_int == 200 assert len(tracked_requests) == 1 tracked_request = tracked_requests[0] assert "username" not in tracked_request.tags
Example #16
Source File: test_django.py From scout_apm_python with MIT License | 5 votes |
def test_urlconf(tracked_requests): new_middleware = ( settings.MIDDLEWARE[:-1] + [__name__ + ".urlconf_middleware"] + settings.MIDDLEWARE[-1:] ) with app_with_scout(MIDDLEWARE=new_middleware) as app: response = TestApp(app).get("/hello/") assert response.status_int == 200 assert len(tracked_requests) == 1 tracked_request = tracked_requests[0] assert tracked_request.tags["urlconf"] == "tests.integration.django_app_second_copy"
Example #17
Source File: middleware.py From openstax-cms with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): # create django request resolver self.handler = BaseHandler() # prevent recursive includes old = settings.MIDDLEWARE name = self.__module__ + '.' + self.__class__.__name__ settings.MIDDLEWARE = [i for i in settings.MIDDLEWARE if i != name] self.handler.load_middleware() settings.MIDDLEWARE = old super(CommonMiddlewareAppendSlashWithoutRedirect, self).__init__(*args, **kwargs)
Example #18
Source File: wagtail_hooks.py From wagtail-2fa with MIT License | 5 votes |
def register_2fa_permission(): if "wagtail_2fa.middleware.VerifyUserPermissionsMiddleware" in settings.MIDDLEWARE: return Permission.objects.filter(content_type__app_label='wagtailadmin', codename='enable_2fa') return Permission.objects.none()
Example #19
Source File: apps.py From simpleui with MIT License | 5 votes |
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
Example #20
Source File: apps.py From simpleui with MIT License | 5 votes |
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 for index, item in enumerate(settings.MIDDLEWARE): if item == 'django.middleware.clickjacking.XFrameOptionsMiddleware': settings.MIDDLEWARE.pop(index) except Exception as e: pass pass
Example #21
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_middleware_not_first(): stdout = compat.StringIO() with override_settings( **middleware_setting(django.VERSION, ("foo", "elasticapm.contrib.django.middleware.TracingMiddleware")) ): call_command("elasticapm", "check", stdout=stdout) output = stdout.getvalue() assert "not at the first position" in output if django.VERSION < (1, 10): assert "MIDDLEWARE_CLASSES" in output else: assert "MIDDLEWARE setting" in output
Example #22
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
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
Example #23
Source File: django_tests.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
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"] == {}
Example #24
Source File: middleware.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def process_request(self, request): # AuthenticationMiddleware is required so that request.user exists. if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the RemoteUserMiddleware class.") try: username = request.META[self.header] except KeyError: # If specified header doesn't exist then remove any existing # authenticated remote-user, or return (leaving request.user set to # AnonymousUser by the AuthenticationMiddleware). if self.force_logout_if_no_header and request.user.is_authenticated: self._remove_invalid_user(request) return # If the user is already authenticated and that user is the user we are # getting passed in the headers, then the correct user is already # persisted in the session and we don't need to continue. if request.user.is_authenticated: if request.user.get_username() == self.clean_username(username, request): return else: # An authenticated user is associated with the request, but # it does not match the authorized user in the header. self._remove_invalid_user(request) # We are seeing this user for the first time in this session, attempt # to authenticate the user. user = auth.authenticate(request, remote_user=username) if user: # User is valid. Set request.user and persist user in the session # by logging the user in. request.user = user auth.login(request, user)
Example #25
Source File: middleware.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
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))
Example #26
Source File: session.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
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)
Example #27
Source File: apps.py From ishare with MIT License | 5 votes |
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
Example #28
Source File: middleware.py From python-sensor with MIT License | 5 votes |
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)
Example #29
Source File: utils.py From django-polaris with Apache License 2.0 | 5 votes |
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))
Example #30
Source File: forms.py From bioforum with MIT License | 5 votes |
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