【问题标题】:how to pass decorated function arguments in decorator如何在装饰器中传递装饰函数参数
【发布时间】:2017-11-20 11:27:40
【问题描述】:

下面有代码

@newrelic.agent.data_store_trace('Mysql', '<name>',None)
def get_user(request=None, name=settings.DEFAULT_NAME):
    # Some implementation

在装饰器中,代替&lt;name&gt;,我想传递装饰函数中的名称。

请注意,我不想修改/覆盖装饰器,因为 newrelic 会不时更新包,这对我们来说是个问题。

有什么办法???

【问题讨论】:

    标签: python newrelic python-decorators


    【解决方案1】:

    装饰器只是简单的包装函数。

    编写另一个包装器函数来包装newrelic.agent.data_store_trace 并允许传递名称。

    说New Relic将data_store_trace定义为:

    import functools
    
    
    def data_store_trace(product, target, operation):
      def wraps(fn):
        @functools.wraps(fn)
        def wrapped(*args, **kwargs):
          print('Tracing: ', fn.__name__, args, kwargs)
          return fn(*args, **kwargs)
        return wrapped
      return wraps
    

    添加另一个级别的间接将给出:

    def data_store_trace_with_name(product, operation, target=''):
      def wraps(fn):
        @functools.wraps(fn)
        def wrapped(*args, **kwargs):
          return data_store_trace(product, target, operation)(fn)(*args, **kwargs)
        return wrapped
      return wraps
    
    @data_store_trace_with_name('Mysql', None, '<name>')
    def add(x, y):
      return x + y
    
    add(5, 6)
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2010-12-30
      • 2017-07-19
      • 2016-02-14
      • 1970-01-01
      • 2018-05-30
      • 2012-06-13
      • 2021-08-06
      • 2020-12-18
      相关资源
      最近更新 更多