我使用New来监视我的Python (2.7)应用程序,但只在我的生产环境中。我想用他们的function_trace装饰器。
在wsgi.py中
try:
import newrelic.agent
newrelic.agent.initialize('/path/')
except Exception as e:
pass在views.py中
if settings.ENV == "test":
pass
else:
import newrelic
@newrelic.agent.function_trace()
def my_function():
....当然,这在生产中很有用,但是在测试中失败了。我不能用if
def newrelic_conditional_decorator(function)
# What magic goes in here...
if settings.ENV == "test":
just return function
else:
use @newrelic.agent.function_trace() decorator
@newrelic_conditional_decorator
def my_function():
....我总是有点模糊的装饰师,所以我希望在这里得到一些帮助!(或者另一种处理测试中不具有与生产中相同的包的方法。)
发布于 2018-03-10 00:22:47
修饰器接收一个函数并从中返回一个新函数。因此,如果您想要一个条件装饰符,则只需在不希望应用装饰符时返回初始函数。
你的具体案例
def newrelic_conditional_decorator(function):
if settings.ENV == "test":
# We do not apply the decorator to the function
return function
else:
# We apply the decorator and return the new function
return newrelic.agent.function_trace()(function)
@newrelic_conditional_decorator
def my_function():
...有点笼统
您可以将其抽象成一个更通用的条件修饰器,它应用给定的生成器,条件是一些condition函数返回True。
def conditional_decorator(decorator, condition, *args):
def wrapper(function):
if condition(*args):
return decorator(function)
else:
return function
return wrapper
@conditional_decorator(
newrelic.agent.function_trace(),
lambda settings: settings.ENV != "test",
settings)
def my_function():
...https://stackoverflow.com/questions/49203954
复制相似问题