django 信号机制

翻译自:django 1.6官方文档。水平有限,如有错误,还望斧正

Django includes a “signal dispatcher” which helps allow decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.

django 包含一个“信号分配器”,它允许在框架内其他地方发生的动作通知到解耦的应用。 简言之,信号(signals)允许某个发送者在某个动作发生时能通知一系列的接受者(receivers)。这在许多部分代码对于相同事件感兴趣(be interested)时十分有用。

Django provides a set of built-in signals that let user code get notified by Django itself of certain actions. These include some useful notifications:
• django.db.models.signals.pre_save & django.db.models.signals.post_save
Sent before or after a model’s save() method is called.
• django.db.models.signals.pre_delete & django.db.models.signals.post_delete
Sent before or after a model’s delete() method or queryset’s delete() method is called.
• django.db.models.signals.m2m_changed
Sent when a ManyToManyField on a model is changed.
• django.core.signals.request_started & django.core.signals.request_finished
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 define and send your own custom signals;

django 提供了一些列内置的信号,使用户的代码能够在某些动作发生时被 Django自己通知到。包括了
一些有用的信号:
    • django.db.models.signals.pre_save & django.db.models.signals.post_save
    在模型的save()方法被调用前后发送;
    • django.db.models.signals.pre_delete & django.db.models.signals.post_delete
    在模型(model)或查询集(qeuryset)的delete()方法被调用前后发送;
    • django.db.models.signals.m2m_changed
    多对多字段被改变时被发送
    •django.core.signals.request_started & django.core.signals.request_finished
    在HTTP请求开始或结束之前被调用
完全版本参考 built-in signal documentation 也可以自定义signals:


Listening to signals:

To receive a signal, you need to register a receiver function that gets called when the signal is sent by using the
Signal.connect() method:
Signal.connect(receiver[, sender=None, weak=True, dispatch_uid=None ])
Parameters
• receiver – The callback function which will be connected to this signal. See Receiver functions for more information.
• sender – Specifies a particular sender to receive signals from. See Connecting to signals
sent by specific senders for more information.
• weak – Django stores signal handlers as weak references by default. Thus, if your receiver
is a local function, it may be garbage collected. To prevent this, pass weak=False when
you call the signal’s connect() method.
• dispatch_uid – A unique identifier for a signal receiver in cases where duplicate signals
may be sent. See Preventing duplicate signals for more information.
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.


监听信号:
    要接收信号,需要注册一个 receiver 函数。这个函数在信号被发送时调用。信号是通过Signal.connect()
    方法发送的:
    Signal.connect(receiver[, sender=None, weak=True, dispatch_uid=None ])
        参数:receiver——是回调函数,被链接到这个信号。
              sender——指定一个特定的发送者
              weak——默认Django 把信号处理器视作弱引用(weak reference)的。若你的receiver是局部函数,
              会回收被垃圾。为防止发生,当connect()调用时传weak=True
              dispatch_uid——receiver的唯一的id,为防止多个信号发送。
    以HTTP request 结束时为例,信号机制如何工作:

Receiver functions
First, we need to define a receiver function. A receiver can be any Python function or method:
def my_callback(sender,**kwargs):
    print("Request finished!")
Notice that the function takes a sender argument, along with wildcard keyword arguments (**kwargs); all signalhandlers must take these arguments.
We’ll look at senders a bit later, 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 assending no arguments, which means we might be tempted to write our signal handling as my_callback(sender).
This would be wrong – in fact, Django will throw an error if you do so. That’s because at any point arguments could get added to the signal and your receiver must be able to handle those new arguments

接收函数:
    定义receiver函数:
    def my_callback(sender,**kwargs):
        print ('request finished')
    所有的信号处理函数都要有 sender和**kwargs参数
    所有的信号都发送 关键字参数,并且会随时改变这些参数。本例中没有**kwargs参数,但是定义处理函数时不
    能不写

Connecting receiver functions
There are two ways you can connect a receiver to a signal. You can take the manual connect route:
from django.core.signals import request_finished
request_finished.connect(my_callback)
Alternatively, you can use a receiver decorator when you define your receiver:

from django.core.signals import request_finished
from django.dispatch import receiver
@receiver(request_finished)
def my_callback(sender,**kwargs):
    print("Request finished!")

Now, our my_callback function will be called each time a request finishes.
Note that receiver can also take a list of signals to connect a function to.
The ability to pass a list of signals was added.

链接接收函数:
    两种方式链接信号和接收函数。
    第一种,人工链接:
    from django.core.signals import request_finished
    request_finished.connect(my_callback)
    第二种,用receiver装饰器
    from django.core.signals import request_finished
    from django.dispatch import receiver
    @receiver(request_finished)
    def my_callback(sender,**kwargs):
        print('request finished')
    现在,my_callback在每次http request结束后都会调用
    receiver函数也可以链接一系列(a list of)的信号。

Where should this code live?
You can put signal handling and registration code anywhere you like. However, you’ll need to make sure that the
module it’s in gets imported early on so that the signal handling gets registered before any signals need to be sent. This
makes your app’s models.py a good place to put registration of signal handlers.

在放置信号处理和注册函数?任何地方。但要保证信号发生前被导入,所以models.py是个选择
链接到指定的发送者:

Connecting to signals sent by specific senders
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
django.db.models.signals.pre_save, the sender will be the model class being saved, so you can indicate that you only want signals sent by some model:

from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel
@receiver(pre_save, sender=MyModel)
def my_handler(sender,**kwargs):
    ...
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.

    某些信号被发送许多次,但你可能只感兴趣其中某个子集。例如,django.db.models.signals.pre_save
    在model被保存时发送。很多时候你不需要知道所有model何时保存——只需要指定的一个。
    这种情况下,你可以注册接收特定的sender发送的信号。这个例子中是django.db.models.signals.pre_save,
    sender是要保存的model类。所以,你可以指明只想要某个model发送的信号:
    from django.db.models.signals import pre_save
    from django.dispatch import receiver
    from myapp.models import MyModel
    @receiver(pre_save,sender=MyModel)
    def my_handler(sender,**kwargs):
        pass
    这样 my_handler函数只有在MyModel实例被保存时才被调用

Preventing duplicate signals
In some circumstances, the module in which you are connecting signals may be imported multiple times. This can
cause your receiver function to be registered more than once, and thus called multiples times for a single signal event.
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.
from django.core.signals import request_finished
request_finished.connect(my_callback, dispatch_uid="my_unique_identifier")

防止复制信号:
    某些情况下,你连接信号的模块会被导入多次。会导致receiver 函数被注册多次,因此一个信号事件会导致多次
    receiver函数的调用。
    如果这是有问题的(比如用model被保存时的信号发送邮件),传一个独特的id作为dispatch_uid参数来确定你的
    接收函数。这个id通常是string,尽管可哈希的对象(hashable)同样满足(suffice)。最终结果是你的接收函数
    将会指被绑定到信号一次,由于dispatch_uid的缘故。
    from django.core.signals import request_finished
    request_finished.connect(my_callback,dispatch_uid='my_unique_identifier')

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

Defining signals
class Signal([providing_args=list ])
All signals are django.dispatch.Signal instances. The providing_args is a list of the names of arguments the signal will provide to listeners. This is purely documentational, however, as there is nothing that checks that
the signal actually provides these arguments to its listeners.
For example:
import django.dispatch
pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
This declares a pizza_done signal that will provide receivers with toppings and size arguments.
Remember that you’re allowed to change this list of arguments at any time, so getting the API right on the first try isn’t necessary

定义、发送信号:
    你的app可以充分利用信号机制,提供自己的信号。
    定义信号:
    class Signal([providing_args=list])
    所有信号都是django.dispatch.Signal的实例,providing_args 是信号提供给监听器的参数名列表。这完全是文档化的。
    但是没有检查,所以信号事实上提供这些参数给监听器。
    例如:
    import django.dispatch
    pizza_done = django.dispatch.Signal(providing_args=('toppings','size'))
    这句话声明了 pizza_done信号将会提供两个参数。
    记住,允许你随时改变这个参数列表,所以第一次就使使API正确没有必要

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() or Signal.send_robust(). 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:
class PizzaStore(object):
    ...
    def send_pizza(self, toppings, size):
        pizza_done.send(sender=self.__class__, toppings=toppings, size=size)
        ...
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.

发送信号:
    两种方法:Signal.send(sender,**kwargs),Signal.send_robust(sender,**kwargs)必须提供发送参数(通常情况下是类),
    和其他的参数。例如:发送pizza_done信号的函数可能如下:
    def send_pizza(self,toppings,size):
        pizza_done.send(sender=self.__class__,toppings=toppings,size=size)
        ...
    send()和send_robust()都返回 tuple对的list,[(receiver,response),...],代表了接收函数和它们的返回值。
    send和send_robust不同之处在于怎样处理由receiver产生的异常。send不捕捉(catch)任何receiver产生的异常,
    只是允许异常传递。因此,
    send_robust捕捉所有从Exception产生的错误,确保所有receiver接收到信号。如果错误发生了,对于错误发生的receiver,
    错误实例会返回到tuple对里。

Disconnecting signals
Signal.disconnect([receiver=None, sender=None, weak=True, dispatch_uid=None ])
To disconnect a receiver from a signal, call Signal.disconnect(). The arguments are as described in
Signal.connect().
The receiver argument indicates the registered receiver to disconnect. It may be None if dispatch_uid is used to
identify the receiver.


断开信号:
    Signal.disconnect([receiver=None,sender=None,weak=True,dispatch_uid=None])
    断开信号和接收者,调用disconnect方法。
    receiver参数表明了要断开的receiver,若指定了dispatch_uid,receiver可以为None



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值