django系列8.3.2--django中间件实现登录验证(2) 个人构想逻辑

middleware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import render,redirect,reverse
from django.shortcuts import HttpResponse


class SessionAuth(MiddlewareMixin):

    def process_request(self,request):
        print("session认证开始")

        white_list = [reverse('login'),]
        path = request.path
        print(path)
        if path in white_list:
            print("直接通过")
            return None
        else:
            status = request.session.get("session_login")
            if status:
                return None
            else:
                return redirect('login')

    def process_response(self, request, response):
        return response

其中process_request函数可以优化为

def process_request(self,request):
     print("session认证开始")

     white_list = [reverse('login'),]  # 设置白名单
     path = request.path
     print(path)
     if path not in white_list:
     status = request.session.get('session_login')
     if not status:
         return redirect('login')

 

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index, name="index"),
    url(r'^login/', views.login, name="login"),
    url(r'^logout/', views.logout, name="logout"),
    # url(r'^loginview/', views.LoginView.as_view(), name="loginview"),
]

 

views.py

def login(request):

    if request.method == 'GET':
        print("app中的视图函数")
        return render(request,"login.html")

    else:
        username = request.POST.get("username")
        password = request.POST.get("password")

        ret_obj_list = models.UserInfo.objects.filter(username=username,password=password)
        if ret_obj_list.exists():
            request.session['session_login'] = True
            request.session['username'] = username

            # data = {"session_login":True,"user":username}
            return redirect("index")
        else:
            return render(request,"login.html")

def index(request):
    return render(request, "index.html")

def logout(request):
    request.session.flush()
    return redirect('login')

 

posted @ 2019-03-08 20:48  robertx  阅读(173)  评论(0编辑  收藏  举报