【问题标题】:Is there any way to get the list of names of views having a decorator, Python, Django有什么方法可以获取具有装饰器、Python、Django 的视图名称列表
【发布时间】:2016-03-15 14:48:28
【问题描述】:

我有一个这样的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"]

请帮助我,在此先感谢。

【问题讨论】:

    标签: python django django-views python-decorators


    【解决方案1】:
    decorated = []
    def myDecorator(fn):
        decorated.append(fn)
        ...
    

    也许?但它只有在它们被装饰后才会起作用(即导入或以其他方式“运行”......如果它们只是坐在某处的 .py 文件中,它将不起作用)

    【讨论】:

      【解决方案2】:

      我想你可以和医生搞点什么。以下是我的解决方案。只是为了你的灵感。你可以试试:)

      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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-15
        • 2018-02-18
        • 2022-08-19
        • 2014-05-22
        • 2020-12-18
        • 2017-11-22
        • 2022-06-15
        • 1970-01-01
        相关资源
        最近更新 更多