django 使用裝飾器驗證用戶登陸


使用裝飾器驗證用戶登陸,需要使用@method_decorator

首先需引用,method_decorator,並定義一個閉包

from django.utils.decorators import method_decorator
def checkLogin(func):
    def wrapper(request,*args,**kwargs):
        is_login=request.session.get('IS_LOGIN',False)
        if is_login:
            return func(request,*args,**kwargs)
        else:
            return  redirect('/Index/')
    return  wrapper

登陸頁面的定義如下例子:

class Login(View):    
    def get(self,request):
        return render(request,'index.html')
    def post(self,request):
        username=request.POST.get('username')
        user_list=Hbuser.objects.filter(username=username).first()
        if user_list:
            request.session['IS_LOGIN']=True
            request.session['uname']=user_list.username
        else:
            request.session.flush()
            return redirect('/Index/')
        return  redirect('/Home/')

裝飾器的使用方法如下,下面是對整個類實用裝飾器

@method_decorator(checkLogin,name='dispatch')
class Home(View):
    def get(self,request):
        return HttpResponse('OK')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM