1. Basic Concepts
Django ships with a signal dispatcher built in. Signals help decouple program modules. When an event occurs elsewhere in the application, a designated function is notified. Signals let certain senders notify a group of receivers that some action has taken place.
2. Using Signals
2.1 Declaring a Signal
Before using a signal, you first have to create a signal instance and declare the list of arguments the signal receives. django.dispatch.Signal is the signal class Django provides; its constructor takes one argument, providing_args, which specifies the arguments the signal contains.
| |
2.2 Sending a Signal
When a receiver needs to be notified to handle a signal, the sender first has to send a signal. The Signal class provides two methods for sending signals.
| |
Both methods return a list of tuples [(receiver, response), … ] representing all the receiver functions and their response values. The difference lies in exception handling: send( ) does not catch exceptions raised by receivers, whereas send_robust( ) does.
| |
2.3 Associating Handler Functions
The first way is to use the connect method.
| |
- receiver: the receiver of the signal
- sender: the sender of the signal
- weak: by default Django stores signal handlers as weak references. As a result, if the receiver function is a local function, it may be garbage collected. To prevent this, specify weak=False.
- dispatch_uid: the unique identifier of the signal handler, for cases where the signal may be sent repeatedly Define a receiver (which you could also call a call_back function):
| |
The second way is to use a decorator.
| |
Decorating with the decorator lets you designate the signal’s handler function. receiver also accepts a sender argument, handling only signals from the designated sender.
The third way is to use the dispatcher.
| |
dispatcher explicitly points out the handler function, the signal, and the sender.
2.3 Handling Signals
Handling a signal is done by calling the handler function.
| |
All signal handler functions must accept a sender argument and wildcard keyword arguments (**kwargs)
2.4 Disconnecting a Signal
| |
If the receiver disconnects successfully, it returns True; otherwise it returns False.
3. Django Built-in Signals
Django’s built-in signals are already-instantiated Signal classes. When you use them, the two steps of declaring a signal and sending a signal are skipped. Simply associate a Django built-in signal directly with a custom handler function and you can use it. Below is the list of Django built-in signals:
django.db.models.signals
| |
django.core.signals
| |
django.test.signals
| |
django.db.backends.signals
| |
For example, if you need to perform some operation after each request finishes, you can write it like this:
| |
4. References
- 1.http://python.usyiyi.cn/translate/django_182/topics/signals.html
- 2.http://lilongzi.blog.51cto.com/5519072/1906557
