CBV装饰校验的三种方式session
代码如下:
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 redirect('/login') return inner #第二种 name参数必须指定 @method_decorator(login_auth,name='get') class MyHome(View): #第三种 只要是在该类中定义的方法都会被指定 @method_decorator(login_auth) def dispatch(self, request, *args, **kwargs): super().dispatch(request,*args,**kwargs) # 第一种 @method_decorator(login_auth) def get(self,request): return HttpResponse('get') def post(self,request): return HttpResponse('home')