信号

    Django provides a that let user code get notified by Django itself of certain actions. These include some useful notifications:

    See the built-in signal documentation for a complete list, and a complete explanation of each signal.

    You can also ; see below.

    To receive a signal, register a receiver function using the Signal.connect() method. The receiver function is called when the signal is sent. All of the signal’s receiver functions are called one at a time, in the order they were registered.

    Signal.``connect(receiver, sender=None, weak=True, dispatch_uid=None)

    Let’s see how this works by registering a signal that gets called after each HTTP request is finished. We’ll be connecting to the request_finished signal.

    First, we need to define a receiver function. A receiver can be any Python function or method:

    Notice that the function takes a sender argument, along with wildcard keyword arguments (**kwargs); all signal handlers must take these arguments.

    We’ll look at senders , but right now look at the **kwargs argument. All signals send keyword arguments, and may change those keyword arguments at any time. In the case of request_finished, it’s documented as sending no arguments, which means we might be tempted to write our signal handling as my_callback(sender).

    Connecting receiver functions

    There are two ways you can connect a receiver to a signal. You can take the manual connect route:

    1. from django.core.signals import request_finished

    Alternatively, you can use a decorator:

    receiver(signal)

    参数:signal — A signal or a list of signals to connect a function to.

    Here’s how you connect with the decorator:

    Now, our function will be called each time a request finishes.

    我的代码该放在哪?

    Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code.

    In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the method of your application configuration class. If you’re using the receiver() decorator, import the signals submodule inside .

    注解

    The ready() method may be executed more than once during testing, so you may want to , especially if you’re planning to send them within tests.

    Some signals get sent many times, but you’ll only be interested in receiving a certain subset of those signals. For example, consider the django.db.models.signals.pre_save signal sent before a model gets saved. Most of the time, you don’t need to know when any model gets saved — just when one specific model is saved.

    In these cases, you can register to receive signals sent only by particular senders. In the case of , the sender will be the model class being saved, so you can indicate that you only want signals sent by some model:

    1. from django.db.models.signals import pre_save
    2. from django.dispatch import receiver
    3. from myapp.models import MyModel
    4. @receiver(pre_save, sender=MyModel)
    5. def my_handler(sender, **kwargs):
    6. ...

    The my_handler function will only be called when an instance of MyModel is saved.

    Different signals use different objects as their senders; you’ll need to consult the built-in signal documentation for details of each particular signal.

    Preventing duplicate signals

    In some circumstances, the code connecting receivers to signals may run multiple times. This can cause your receiver function to be registered more than once, and thus called as many times for a signal event. For example, the method may be executed more than once during testing. More generally, this occurs everywhere your project imports the module where you define the signals, because signal registration runs as many times as it is imported.

    If this behavior is problematic (such as when using signals to send an email whenever a model is saved), pass a unique identifier as the dispatch_uid argument to identify your receiver function. This identifier will usually be a string, although any hashable object will suffice. The end result is that your receiver function will only be bound to the signal once for each unique dispatch_uid value:

    Your applications can take advantage of the signal infrastructure and provide its own signals.

    Signals are implicit function calls which make debugging harder. If the sender and receiver of your custom signal are both within your project, you’re better off using an explicit function call.

    class Signal

    All signals are instances.

    例如:

    1. import django.dispatch
    2. pizza_done = django.dispatch.Signal()

    This declares a pizza_done signal.

    Sending signals

    There are two ways to send signals in Django.

    Signal.``send(sender, \*kwargs*)

    Signal.``send_robust(sender, \*kwargs*)

    To send a signal, call either Signal.send() (all built-in signals use this) or . You must provide the sender argument (which is a class most of the time) and may provide as many other keyword arguments as you like.

    For example, here’s how sending our pizza_done signal might look:

    Both send() and send_robust() return a list of tuple pairs [(receiver, response), ... ], representing the list of called receiver functions and their response values.

    send() differs from send_robust() in how exceptions raised by receiver functions are handled. send() does not catch any exceptions raised by receivers; it simply allows errors to propagate. Thus not all receivers may be notified of a signal in the face of an error.

    send_robust() catches all errors derived from Python’s Exception class, and ensures all receivers are notified of the signal. If an error occurs, the error instance is returned in the tuple pair for the receiver that raised the error.

    The tracebacks are present on the __traceback__ attribute of the errors returned when calling send_robust().

    Signal.``disconnect(receiver=None, sender=None, dispatch_uid=None)

    To disconnect a receiver from a signal, call . The arguments are as described in Signal.connect(). The method returns True if a receiver was disconnected and False if not.

    The receiver argument indicates the registered receiver to disconnect. It may be None if is used to identify the receiver.