信号在django1.1测试服务器中多次注册 [英] Signals registered more than once in django1.1 testserver

查看:146
本文介绍了信号在django1.1测试服务器中多次注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的models.py文件中定义了一个信号处理函数。在该文件的底部,我使用 signals.post_save.connect(myhandler,sender = myclass) .djangoproject.com / en / dev / topics / signals /rel =nofollow noreferrer> http://docs.djangoproject.com/en/dev/topics/signals/



但是,当我运行测试服务器时,简单的print-statement调试显示models.py文件被导入两次(据我所知),这使得我的信号处理程序得到注册了两次这意味着每个操作都被处理两次,这显然不是预期的行为。



第一次导入似乎是在模型检查阶段发生的,第二次发生在正确的时候在服务器处理的第一个请求期间,模型本身是需要的。



我应该在其他地方注册我的信号处理程序吗?这是1.1测试服务器中的错误吗?我还缺少别的东西吗?

解决方案

connect 方法的签名是

  def connect(self,receiver,sender = None,weak = True,dispatch_uid = None)

其中 dispatch_uid 参数是用于唯一标识特定实例的标识符的接收器。这通常是一个字符串,尽管它可能是任何可写的。如果接收者有一个 dispatch_uid 属性,那么如果另外一个接收者已经存在 dispatch_uid p>

因此,您可以在 connect 中指定一个 dispatch_uid 看看是否消除了这个问题。


I've defined a signal handler function in my models.py file. At the bottom of that file, I use signals.post_save.connect(myhandler, sender=myclass) as recommended in the docs at http://docs.djangoproject.com/en/dev/topics/signals/.

However, when I run the test server, simple print-statement debugging shows that the models.py file gets imported twice and (as far as I can tell), this causes my signal handler to get registered twice. This means that every action is handled twice, which is obviously not the intended behaviour.

The first import seems to occur during the model checking phase, and the second happens right when the model itself is needed during the first request handled by the server.

Should I be registering my signals handlers elsewhere? Is this a bug in the 1.1 test server? Am I missing something else?

解决方案

The signature for the connect method is

def connect(self, receiver, sender=None, weak=True, dispatch_uid=None)

where the dispatch_uid parameter is an identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. If receivers have a dispatch_uid attribute, the receiver will not be added if another receiver already exists with that dispatch_uid.

So, you could specify a dispatch_uid in your connect call to see if that eliminates the problem.

这篇关于信号在django1.1测试服务器中多次注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆