信号

    Django provides a set of built-in signals that let usercode get notified by Django itself of certain actions. These include some usefulnotifications:

    Sent before or after a model's methodis called.

    Sent before or after a model's delete()method or queryset's method is called.

    Sent when a on a model is changed.

    Sent when Django starts or finishes an HTTP request.

    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 theSignal.connect() method. The receiver function is called when the signalis sent.

    • 参数:
      • receiver — The callback function which will be connected to thissignal. See for more information.
      • sender — Specifies a particular sender to receive signals from. SeeConnecting to signals sent by specific senders for more information.
      • weak — Django stores signal handlers as weak references bydefault. Thus, if your receiver is a local function, it may begarbage collected. To prevent this, pass weak=False when you callthe signal's connect() method.
      • dispatch_uid — A unique identifier for a signal receiver in caseswhere duplicate signals may be sent. See for more information.

    Let's see how this works by registering a signal thatgets called after each HTTP request is finished. We'll be connecting to therequest_finished signal.

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

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

    We'll look at senders , but right now look at the **kwargsargument. All signals send keyword arguments, and may change those keywordarguments at any time. In the case ofrequest_finished, it's documented as sending noarguments, which means we might be tempted to write our signal handling asmy_callback(sender).

    Connecting receiver functions

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

    1. from django.core.signals import request_finished
    2.  
    3. request_finished.connect(my_callback)

    Alternatively, you can use a receiver() decorator:

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

    Here's how you connect with the decorator:

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

    我的代码该放在哪?

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

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

    注解

    The ready() method may be executed more thanonce during testing, so you may want to , especially if you're planningto send them within tests.

    Some signals get sent many times, but you'll only be interested in receiving acertain subset of those signals. For example, consider thedjango.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 — justwhen one specific model is saved.

    In these cases, you can register to receive signals sent only by particularsenders. In the case of , the senderwill be the model class being saved, so you can indicate that you only wantsignals 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.  
    5. @receiver(pre_save, sender=MyModel)
    6. def my_handler(sender, **kwargs):
    7. ...

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

    Preventing duplicate signals

    In some circumstances, the code connecting receivers to signals may runmultiple times. This can cause your receiver function to be registered morethan once, and thus called multiple times for a single signal event.

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

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

    • class Signal(providing_args=list)
    • All signals are instances. Theproviding_args is a list of the names of arguments the signal will provideto listeners. This is purely documentational, however, as there is nothing thatchecks that the signal actually provides these arguments to its listeners.

    例如:

    1. import django.dispatch
    2.  
    3. pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])

    This declares a pizza_done signal that will provide receivers withtoppings and size arguments.

    Remember that you're allowed to change this list of arguments at any time, sogetting the API right on the first try isn't necessary.

    Sending signals

    There are two ways to send signals in Django.

    • Signal.send(sender, **kwargs)
    • sendrobust(_sender, **kwargs)
    • To send a signal, call either (all built-in signals usethis) or Signal.send_robust(). You must provide the sender argument(which is a class most of the time) and may provide as many other keywordarguments 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 receiverfunctions and their response values.

    send() differs from sendrobust() in how exceptions raised by receiverfunctions are handled. send() does _not catch any exceptions raised byreceivers; it simply allows errors to propagate. Thus not all receivers maybe 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, theerror instance is returned in the tuple pair for the receiver that raised the error.

    The tracebacks are present on the traceback attribute of the errorsreturned when calling send_robust().

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