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