在Python中检测Decorator

时间:2011-04-01 15:31:59

标签: python django django-views

在python中,是否可以检测另一个函数上是否有装饰器?

具体来说,我正在尝试(在django中)编写一些中间件,它将检测正在处理的视图是否已包装在@login_required装饰器中。

class SomeMiddleware(object):

    def process_view(self, request, view_func, view_args, view_kwargs):
        if has_decorator(view_func):
            print "this view was decorated"

我想填写的是“has_decorator”部分....

这可能吗?

1 个答案:

答案 0 :(得分:3)

在shell中只是一些快速的愚弄,表明函数的func_closure属性在未修饰的函数上是空的,但包含装饰函数中的数据。不是100%肯定这一直是真的,但也许这适合你。