我有像这样的views.py文件
views.py
@my_decorator
def a(request):
return HttpResponse("success")
@my_decorator
def b(request):
return HttpResponse("success")
@my_decorator
def c(request):
return HttpResponse("success")
@my_decorator
def d(request):
return HttpResponse("success")
@my_another_decorator
def e(request):
return HttpResponse("success")
我想获得一个包含装饰器“my_decorator”的视图列表
示例:
views_list_with_my_decorator=["a","b","c","d"]
请提前帮助我。
答案 0 :(得分:1)
decorated = []
def myDecorator(fn):
decorated.append(fn)
...
可能?但它只会在它们被装饰后才会起作用(即导入或以其他方式“运行”......如果它们只是坐在某处的.py文件中它将无法工作)
答案 1 :(得分:1)
我认为你可以用docorator做一些技巧。以下是我的解决方案。只是为了你的灵感。你可以尝试一下:)
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrap_func(*args, **kwargs):
return func()
wrap_func.decorator = my_decorator.func_name
return wrap_func
def my_another_decorator(func):
@wraps(func)
def wrap_func(*args, **kwargs):
return func()
wrap_func.decorator = my_another_decorator.func_name
return wrap_func
@my_decorator
def a(request):
pass
@my_decorator
def b(request):
rpass
@my_decorator
def c(request):
pass
@my_decorator
def d(request):
pass
@my_another_decorator
def e(request):
pass
func_list_with_my_decorator = [e for e in globals().values() if getattr(e, 'decorator', None)=='my_decorator']
print func_list_with_my_decorator
如果你想尝试一个函数是否有装饰器,请执行以下操作:
print a.decorator == 'my_decorator'