django信号.如何创建唯一的调度ID? [英] django signals. how to create a unique dispatch id?

查看:48
本文介绍了django信号.如何创建唯一的调度ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时django中的信号被触发两次.在文档中说,创建(唯一的) dispatch_uid 的一种好方法是模块的路径或名称[1]或任何可哈希对象的ID [2].

今天我尝试了这个:

 导入时间my_signal.connect(my_function,dispatch_uid = str(time.time())) 

但是,恐怕在多用户环境中(例如网站).这可能是坏的.在多用户环境中创建此类ID的一种好而安全的方法是什么?

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

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

解决方案

将时间用作调度ID无效.问题不在于您的环境是否是多用户.就是连接信号的代码是否被多次导入.

说模块两次导入,间隔5秒.您已经有效地完成了以下操作.

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

您的信号已使用不同的调度ID连接两次.Django 1.3和更早版本的默认项目结构允许进行这种双重导入,因为模块通常可以作为 project.my_app.module my_app.module 导入.

如果您按照Dmitry的建议选择诸如 my_app.models.function_name 之类的约定,则第二次导入该模块时,信号将不会连接两次,因为调度ID并未更改.由您决定不要重复使用相同的调度ID来用相同的信号注册不同的回调函数.

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

解决方案

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.

这篇关于django信号.如何创建唯一的调度ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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