django signals. how to create a unique dispatch id?

自闭症网瘾萝莉.ら 提交于 2019-12-11 02:39:48

问题


sometimes signals in django are triggered twice. In the docs it says that a good way to create a (unique) dispatch_uid is either the path or name of the module[1] or the id of any hashable object[2].

Today I tried this:

import time
my_signal.connect(my_function, dispatch_uid=str(time.time()))

However I am afraid that in a multiuser environment (like in the case of a web site). This might be broken. What is a good and safe way to create such an id in a multiuser environment?

[1] https://code.djangoproject.com/wiki/Signals

[2] https://docs.djangoproject.com/en/dev/topics/signals/#preventing-duplicate-signals


回答1:


Using the time as a dispatch id won't work. The issue isn't whether your environment is multi-user or not. It's whether the code that connects the signals is imported more than once.

Say your module was imported twice, 5 seconds apart. You have effectively done the following.

my_signal.connect(my_function, dispatch_uid=1332407342.51)
my_signal.connect(my_function, dispatch_uid=1332407352.51)

Your signal has been connected twice with different dispatch ids. This default project structure for Django 1.3 and earlier allows this double import to occur, as modules can often be imported as project.my_app.module and my_app.module.

If you choose a convention like my_app.models.function_name as Dmitry suggests, then the second time the module is imported, the signal will not be connected twice because the dispatch id has not changed. It's up to you not to reuse the same dispatch id to register different callback functions with the same signal.




回答2:


Just use string to the module, like 'apps.models.signal_name'



来源:https://stackoverflow.com/questions/9813156/django-signals-how-to-create-a-unique-dispatch-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!