我正在尝试构建一个基于装饰器的调度程序,例如Flask或Pyramid使用的调度程序。我得到了一些有效的东西,但遇到了一些问题22。以下代码有效,但仅限于执行foo()并设置.mq_path属性。在启动应用程序并构建可分派功能列表时,尚未设置任何属性。我想执行由事件驱动的foo()。
我可以"手动"准备一个函数列表并在我添加函数时更新,但我喜欢Flask的工作方式,只需将一个装饰器添加到一个处理URL的函数(或者在这种情况下是一个MQ路径)。
list_of_paths = []
path_dispatcher = {}
def handle_mq(path):
def decorator(fn):
def decorated(*args,**kwargs):
decorated.mq_path = path
print "Hello from the handle_mq() decorator, your path is: {0}".format(path)
return fn(*args,**kwargs)
return decorated
return decorator
@handle_mq('/some/path')
def foo():
print "foo!"
foo() # <- this code only works if I first call the decorated function
for k, v in globals().items():
if hasattr(v, 'mq_path'):
list_of_paths.append(v.mq_path)
path_dispatcher[v.mq_path] = v
print list_of_paths
print path_dispatcher
path_dispatcher['/some/path']()
基本上问题是,如何在首次执行之前收集已修饰函数的列表?
我在使用Python 2.7。
答案 0 :(得分:0)
我找到了答案!
list_of_paths = []
path_dispatcher = {}
def handle_mq(path):
def decorator(fn):
list_of_paths.append(path)
path_dispatcher[path] = fn
def decorated(*args,**kwargs):
print "Hello from handl_mq decorator, your path is: {0}".format(path)
return fn(*args,**kwargs)
return decorated
return decorator
@handle_mq('/some/path')
def foo():
print "foo!"
print list_of_paths
print path_dispatcher
path_dispatcher['/some/path']()