首页 > 代码库 > django signal 浅析
django signal 浅析
默认的signals极其参数
(django 1.6.5)
模型的(django/db/models/signal.py):
from django.dispatch import Signalclass_prepared = Signal(providing_args=["class"])pre_init = Signal(providing_args=["instance", "args", "kwargs"], use_caching=True)post_init = Signal(providing_args=["instance"], use_caching=True)pre_save = Signal(providing_args=["instance", "raw", "using", "update_fields"], use_caching=True)post_save = Signal(providing_args=["instance", "raw", "created", "using", "update_fields"], use_caching=True)pre_delete = Signal(providing_args=["instance", "using"], use_caching=True)post_delete = Signal(providing_args=["instance", "using"], use_caching=True)pre_syncdb = Signal(providing_args=["app", "create_models", "verbosity", "interactive", "db"])post_syncdb = Signal(providing_args=["class", "app", "created_models", "verbosity", "interactive", "db"])m2m_changed = Signal(providing_args=["action", "instance", "reverse", "model", "pk_set", "using"], use_caching=True)
用户登录的(django/contrib/auth/signals.py)
from django.dispatch import Signaluser_logged_in = Signal(providing_args=[‘request‘, ‘user‘])user_login_failed = Signal(providing_args=[‘credentials‘])user_logged_out = Signal(providing_args=[‘request‘, ‘user‘])
关于request请求的(django/core/signals.py)
from django.dispatch import Signalrequest_started = Signal()request_finished = Signal()got_request_exception = Signal(providing_args=["request"])
数据库连接的(django/db/backends/signals.py)
from django.dispatch import Signalconnection_created = Signal(providing_args=["connection"])
原理
简图
Signal类和receiver修饰符位于 django/dispatch/dispatcher.py中。
关于模型的signals的触发实际看django/db/modes/base.py 中的Model类,例如 post_save(579~582)如下:
# Signal that the save is complete if not meta.auto_created: signals.post_save.send(sender=origin, instance=self, created=(not updated), update_fields=update_fields, raw=raw, using=using)
小结
1. 实际上signals的设计是一个很松的耦合的设计。
可以说, post_save和save没有半毛钱的关系,如果你在save的最后代码里触发它,它名副其实。
当然你也可以在其他任意的层级,任意位置触发它。
2. 本质上讲, 就是一个 list of function, 然后这个list有一个名字, 然后你可以在任意位置,任意时机调用list中的function.
转载请注明本文来自:http://www.cnblogs.com/Tommy-Yu/p/4101575.html,谢谢!
django signal 浅析
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。