Three ways to check the session CBV decoration

code show as below:

from django.shortcuts import render,HttpResponse,redirect
from django.views import View
# Create your views here.


def login(request):
    if request.method == 'POST':
        username = request.POST.get('name')
        password = request.POST.get('password')
        if username == 'jason' and password == '123':
            request.session['name'] = 'jason'
            return redirect('/home')
    return render(request,'login.html')


# 要用装饰器需要导的模块
from functools import wraps
from django.utils.decorators import method_decorator
def login_auth(func):
    @wraps(func)
    def inner(request,*args,**kwargs):
        if request.session.get('name'):
             Return FUNC (* args, ** kwargs)
         return the redirect ( ' / Login ' )
     return Inner 

# second parameter name must be specified 
@method_decorator (login_auth, name = ' GET ' )
 class MyHome (View):
     # third species as long as the methods defined in the class will be designated 
    @method_decorator (login_auth)
     DEF dispatch (Self, Request, * args, ** kwargs): 
        . Super () dispatch (Request, * args, ** kwargs)
     # of one kind 
    @method_decorator (login_auth)
     DEF get(self,request):
        return HttpResponse('get')

    def post(self,request):
        return HttpResponse('home')

 

Guess you like

Origin www.cnblogs.com/HUIWANG/p/11047221.html