装饰器

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):

 

 
 

相关文章:

  • 2021-06-06
  • 2021-11-14
  • 2022-12-23
  • 2018-06-12
  • 2022-12-23
  • 2018-08-10
  • 2021-12-18
猜你喜欢
  • 2022-12-23
  • 2022-01-23
  • 2022-02-13
  • 2020-05-29
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
相关资源
相似解决方案