Django 视图添加装饰器

装饰器

from functools import wraps


def timer(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        start = time.time()
        ret = func(request, *args, **kwargs)
        print(f'执行时间是:{time.time() - start}')
        return ret
    return inner

 

视图分类

FBV

CBV

FBV 添加装饰器

直接添加在函数上就行

CBV 添加装饰器

需要使用一个装饰器

from django.utils.decorators import method_decorator
  • 加在方法上
@method_decorator(timer)
def get(self, request):
  • 加在dispath方法上
# 方式1
@method_decorator(timer, name='dispatch')
class Art(View):
    def dispatch(self, request, *args, **kwargs):
        ret = super().dispatch(request, *args, **kwargs)
        return ret
    
    def get(self,request):
        pass
    
    def post(self,request):
        pass



# 方式2
from django.views import View
from django.utils.decorators import method_decorator


class Art(View):
    @method_decorator(timer)
    def dispatch(self, request, *args, **kwargs):
        ret = super().dispatch(request, *args, **kwargs)
        return ret

    def get(self,request):
        pass

    def post(self,request):
        pass

 

  • 加在类上
from django.views import View
from django.utils.decorators import method_decorator


@method_decorator(timer, name='get')  # 加在get方法上
@method_decorator(timer, name='post') # 加在post方法上
class Art(View):

 

 
 
posted @ 2021-07-26 11:25  Star-Hitian  阅读(104)  评论(0编辑  收藏  举报