django signal 浅析
默认的signals极其参数
(django 1.6.5)
模型的(django/db/models/signal.py):
from django.dispatch import Signal class_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 Signal user_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 Signal request_started = Signal() request_finished = Signal() got_request_exception = Signal(providing_args=["request"])
数据库连接的(django/db/backends/signals.py)
from django.dispatch import Signal connection_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.
3. 触发对象,如果在修饰function的时候有传参数sender,则只有此类型的实例才能够触发该signal
转载请注明本文来自:http://www.cnblogs.com/Tommy-Yu/p/4101575.html,谢谢!