CBV+装饰器

Posted jianhaozhou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CBV+装饰器相关的知识,希望对你有一定的参考价值。

装饰器代码

def login_auth(func):
    def wrapper(request, *args, **kwargs):
        url = request.get_full_path()
        if request.method == ‘GET‘:
            user = request.session.get(‘name‘)
            if user:
                res = func(request, *args, **kwargs)
                return res
            else:
                return redirect(‘/login/?next=%s‘ % url)
        if request.method == ‘POST‘:
            res = func(request, *args, **kwargs)
            return res

    return wrapper

用此装饰器装饰CBV视图函数

1.导入method_decorator

from django.utils.decorators import method_decorator

2.使用方式一(给类中的方法加装饰器)

class Dingdang(View):
    @method_decorator(login_authc)
    def get(self,request):
        user = request.session.get(‘name‘)
        return render(request, ‘dingdang.html‘, locals())
    def post(self, request):
        if json.loads(request.body.decode(‘utf-8‘)) == ‘exit‘:
            request.session.flush()
            return HttpResponse(json.dumps(‘s‘))
        else:
            return HttpResponse(json.dumps(‘操作有误!‘))

3.使用方式二(给类加装饰器)

@method_decorator(login_authc,name=‘get‘)
class Dingdang(View):
    def get(self,request):
        user = request.session.get(‘name‘)
        return render(request, ‘dingdang.html‘, locals())
    def post(self, request):
        if json.loads(request.body.decode(‘utf-8‘)) == ‘exit‘:
            request.session.flush()
            return HttpResponse(json.dumps(‘s‘))
        else:
            return HttpResponse(json.dumps(‘操作有误!‘))

以上是关于CBV+装饰器的主要内容,如果未能解决你的问题,请参考以下文章

Django - 将参数传递给 CBV 装饰器的正确方法?

forms组件cookie与session视图函数(CBV)如何添加装饰器

forms组件cookie与session视图函数(CBV)如何添加装饰器

视图函数:CBV与FBV (ps:补充装饰器)

添加登录装饰器的两种方式:FBV和CBV

django补充CBV和FBV模式