CBV 验证装饰器的使用

下面是3种方式: 

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


class Login(View):

    def get(self, request):
        return render(request, 'login.html')


def check_login(func):
    def inner(request, *args, **kwargs):
        if request.session.get('user_info'):
            return func(request, *args, **kwargs)
        else:
            return redirect('/login.html')
    return inner

from django.utils.decorators import method_decorator

@method_decorator(check_login, name='dispatch')
class Index(View):

    @method_decorator(check_login)
    def dispatch(self, request, *args, **kwargs):
        return super(Index,self).dispatch( request, *args, **kwargs)

    @method_decorator(check_login)
    def get(self, request):
        return render(request, 'index.html')

    def post(self, request):
        return render(request, 'index.html')

  

原文地址:https://www.cnblogs.com/wumingxiaoyao/p/6529963.html