码迷,mamicode.com
首页 > 其他好文 > 详细

CBV+装饰器

时间:2018-11-23 10:12:05      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:res   *args   response   cal   end   method   dir   tor   login   

装饰器代码

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+装饰器

标签:res   *args   response   cal   end   method   dir   tor   login   

原文地址:https://www.cnblogs.com/jianhaozhou/p/10005667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!