zoukankan      html  css  js  c++  java
  • 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('操作有误!'))
    
  • 相关阅读:
    sql server获取指定库下的所有表名
    sql根据字符将一行拆成多行
    刷题416. Partition Equal Subset Sum
    刷题394. Decode String
    刷题347. Top K Frequent Elements
    刷题309. Best Time to Buy and Sell Stock with Cooldown
    刷题338. Counting Bits
    刷题337. House Robber III
    刷题312. Burst Balloons
    刷题621. Task Scheduler
  • 原文地址:https://www.cnblogs.com/jianhaozhou/p/10005667.html
Copyright © 2011-2022 走看看