django登录需要整个网站无法正常工作

时间:2016-12-19 00:19:41

标签: python django django-views django-settings django-middleware

如果用户尚未通过身份验证,我正在尝试使用代码强制登录。我尝试了太多的代码而我无法让它们工作,因为大多数代码都是用旧版本的django编写的。我正在使用django 1.10.3。

我在运行服务器时没有收到任何错误,但是当我没有登录时,我也没有被重定向到登录页面。我甚至不确定我们可以在设置文件中同时拥有MIDDLEWARE和MIDDLEWARE_ClASSES。任何帮助,将不胜感激。我也希望有一些例外情况,我可以公开一些不需要登录的公开视图

middleware.py:

from builtins import hasattr, any
from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile

EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware:
    """
    Middleware that requires a user to be authenticated to view any page other
    than LOGIN_URL. Exemptions to this requirement can optionally be specified
    in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
    you can copy from your urls.py).

    Requires authentication middleware and template context processors to be
    loaded. You'll get an error if they aren't.
    """
    def process_request(self, request):
        assert hasattr(request, 'user'), "The Login Required middleware\
 requires authentication middleware to be installed. Edit your\
 MIDDLEWARE_CLASSES setting to insert\
 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
 work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
 'django.core.context_processors.auth'."
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(settings.LOGIN_URL)

setting.py:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'heaven.LoginRequiredMiddleware',
]

1 个答案:

答案 0 :(得分:1)

Django改变了Django 1.10的中间件逻辑。 Django 1.10有一种新方法。 here

我的中间件类。它正在运作

# Below middleware class for Django1.10
  class StatisticMiddleware:
      def __init__(self, get_response):
          self.get_response = get_response
      # One-time configuration and initialization.

      def __call__(self, request):
          # Code to be executed for each request before
          # the view (and later middleware) are called.

          response = self.get_response(request)

          self.__model_object_statistics(request, response)

          return response
      def __model_object_statistics(self, request, response):
          # My algorithms