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('操作有误!'))
posted @ 2018-11-23 09:39  周建豪  阅读(178)  评论(0编辑  收藏  举报