django-login-required-middleware WSGI 错误

django-login-required-middleware WSGI error

我正在尝试将这种方式应用到我的项目中:

http://onecreativeblog.com/post/59051248/django-login-required-middleware

这是我的 settings.py:

...

LOGIN_URL = '/admin/login/'

LOGIN_EXEMPT_URLS = (
)

MIDDLEWARE = [
    ...
    'project.middleware.LoginRequiredMiddleware',
]

...

这是我的 middleware.py:

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)

我把 middleware.py 放在我的项目根目录下。

project
|__db.sqlite3
|__manage.py
|__middleware.py
|__app
   |___admin.py
   |___views.py
   |___models.py

但是我得到一个错误。

django.core.exceptions.ImproperlyConfigured: WSGI application 
'project.wsgi.application' could not be loaded; Error importing 
module: 'No module named 'project.middleware'

project 目录(包括 manage.py 的目录)在 python 路径上。因此,您不应在该目录中包含模块的 project. 前缀。

将您的 MIDDLEWARE 设置更改为:

MIDDLEWARE = [
    ...
    'middleware.LoginRequiredMiddleware',
]

最好使用 login_required 装饰器而不是中间件。因为中间件将针对每个请求执行。因此,只需使用 login_required 装饰器装饰视图即可。

from django.contrib.auth.decorators import login_required

@login_required
def user_detail(request):
    # some code