Django中装饰器的使用方法

装饰器的作用(简而言之):让其他函数在不需要做任何代码变动的前提下增加额外的功能

FBV加装饰器

例:以统计时间的装饰器为例

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

其中:timer为装饰器的名字(读者可自定义);func为需要被装饰的函数名字(一般写这个);inner也是自定义,但习惯写inner;*args, **kwargs为要被装饰的函数参数。

使用方式:

@timer
def xx(request):
    ....

 即:在需要的方法上加 @timer即可。

 

CBV加装饰器(共有3种方法,这里本人只列举其中2种方法,但是够了)

注:这里需要再使用一个装饰器(不加也没关系,但是最好还是加上去)

from django.utils.decorators import method_decorator

例:还是以统计时间的装饰器为例

方法一:

class Xxx(View):
    @method_decorator(timer)
    def xx(self, request):
        ....

注:方法一比较简单,只需在定义函数上面加上 @method_decorator(timer) 即可

方法二:

@method_decorator(timer, name='xx')
class Xxx(View):
    def xx(self, request):
        ....

注:方法二也不难,在类的上面加上 @method_decorator(timer, name='xx') 即可,其中 name='xx' 中的  'xx' 为读者自定的方法名

望读者细心阅之。

posted @ 2021-05-06 20:58  Erudite  阅读(440)  评论(0编辑  收藏  举报