【发布时间】:2014-04-12 16:13:45
【问题描述】:
我一直在尝试一种在运行时处理信号创建的方法,我想出了以下代码,它从配置/表中读取并注册 post_save 连接
def _send_to_messaging_notify(**kwargs):
""" _send_to_messaging_notify
"""
if kwargs.get('created'):
instance = kwargs.get('instance')
ct = ContentType.objects.get_for_model(instance)
notify.apply_async(args=[instance.pk, ct.pk, kwargs.get('when')])
def create_function(name, args):
def y(**kwargs):
kwargs.update({'when': inspect.stack()[0][3]})
print 'signal executed on {0}'.format(kwargs.get('sender'))
_send_to_messaging_notify(**kwargs)
y_code = types.CodeType(args, \
y.func_code.co_nlocals, \
y.func_code.co_stacksize, \
y.func_code.co_flags, \
y.func_code.co_code, \
y.func_code.co_consts, \
y.func_code.co_names, \
y.func_code.co_varnames, \
y.func_code.co_filename, \
name, \
y.func_code.co_firstlineno, \
y.func_code.co_lnotab)
return types.FunctionType(y_code, y.func_globals, name)
def load_signals():
""" load_signals
"""
from default_senders import senders
#
for k in senders.iterkeys():
post_save.connect(create_function(str(k), 0), sender=load_model(senders[k].get('default_content_type')),
dispatch_uid=k)
load_signals()
create_function是在运行时创建信号处理器,然后用post_save.connect调用
当我尝试执行此操作时
myfunc = create_function(str(k), 0)
myfunc(sender='xxx')
它工作正常,但是当连接到 post_save.connect 时,当目标模型收到 post_save 操作时它什么也不做。有什么想法吗?谁能给点建议
【问题讨论】:
标签: django