中间件跳转到登陆页面

网站需要登陆才提供服务,因此需要在未登录时跳转到登陆页面.

本网站在登陆之后会存username的cookie, 因此通过检测该cookie是否存在判断用户是否登陆

自定义的middleware写在login下
login目录结构如下


中间件跳转到登陆页面_第1张图片
20180326181811.png

setting中增加middleware最后一条

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'login.LoginMiddleware.QtsAuthenticationMiddleware',
]

装饰器代码

# coding=utf-8

from django.shortcuts import render,HttpResponse,redirect,HttpResponseRedirect

try:
    from django.utils.deprecation import MiddlewareMixin  # Django 1.10.x
except ImportError:
    MiddlewareMixin = object  # Django 1.4.x - Django 1.9.x

class QtsAuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):

        if request.path != '/login/':
            if  request.COOKIES.get('username',None):
                pass
            else:
                return HttpResponseRedirect('/login/')

这样就可以实现未登录时跳转到登陆页面

你可能感兴趣的:(中间件跳转到登陆页面)