Sinyal¶
Django menyertakan sebuah "signal dispatcher" yang membantu mengizinkan aplikasi dipisahkan mendapat pemberitahuan ketika tindakan muncul di tempat lain di kerangka kerja. Dalam kulit kacang, sinyal mengizinkan pengirim tertentu untuk memberitahu beberapa tindakan telah diambil. Mereka adalah khususnya berguna ketika banyak potongan dari kode mungkin tertarik di acara yang sama.
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
Terkirim sebelum atau sesudah model cara
save()
dipanggil.django.db.models.signals.pre_delete
&django.db.models.signals.post_delete
Sent before or after a model's
delete()
method or queryset'sdelete()
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; see below.
Mendengarkan ke sinyal¶
To receive a signal, register a receiver function using the
Signal.connect()
method. The receiver function is called when the signal
is sent.
-
Signal.
connect
(receiver, sender=None, weak=True, dispatch_uid=None)[sumber]¶ Parameter: - receiver -- The callback function which will be connected to this signal. See Fungsi penerima 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'sconnect()
method. - dispatch_uid -- A unique identifier for a signal receiver in cases where duplicate signals may be sent. See Mencegah sinyal rangkap 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.
Fungsi penerima¶
Pertama, kami butuh menentukan fungsi penerima. Penerima dapat menjadi fungsi Phyton apapun atau cara:
def my_callback(sender, **kwargs):
print("Request finished!")
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 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 as sending 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.
Menyambung fungsi penerima¶
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)
Cara lain, anda dapat menggunakan penghias receiver()
:
-
receiver
(signal)[sumber]¶ Parameter: signal -- A signal or a list of signals to connect a function to.
Here's how you connect with the decorator:
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.
Dimana seharusnya kode ini tinggal?
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 ready()
method of your
application configuration class. If you're using the receiver()
decorator, simply import the signals
submodule inside
ready()
.
Catatan
The ready()
method may be executed more than
once during testing, so you may want to guard your signals from
duplication, especially if you're planning
to send them within tests.
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.
Mencegah sinyal rangkap¶
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 multiple times for a single signal event.
Jika perilaku ini bermasalah (seperti ketika menggunakan sinyal mengirim surel dimanapun model disimpan), lewati penciri unik sebagai argumen dispatch_uid
untuk mencirikan fungsi penerima anda. Penciri ini akan biasanya berupa string, meskipun obyek apapun yang mampu akan cukup. Hasil akhir adalah fungsi penerima anda akan hanya diikatkan ke sinyal sekali untuk setiap nilai dispatch_uid
unik:
from django.core.signals import request_finished
request_finished.connect(my_callback, dispatch_uid="my_unique_identifier")
Menentukan dan mengirim sinyal¶
Aplikasi anda dapat mengambil keuntungan dari infrastruktur sinyal dan menyediakan sinyal sendiri.
Menentukan sinyal¶
Semua sinyal adalah instance django.dispatch.Signal
. providing_args
adalah daftar dari nama-nama dari argumen sinyal akan menyediakan ke pendengar. Ini murni dokumentasi, bagaimanapun, ketika tidak ada yang memeriksa sinyal itu sebenarnya menyediakan argumen ini ke pendengarnya.
Sebagai contoh:
import django.dispatch
pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
Ini menyatakan sebuah sinyal pizza_done
yang akan menyediakan penerima dengan argumen toppings
dan size
.
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.
Mengirim sinyal¶
Terdapat dua jalan mengirim sinyal di Django.
To send a signal, call either Signal.send()
(all built-in signals use
this) 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.
Sebagai contoh, ini adalah bagaimana mengirim sinyal pizza_done
kami mungkin terlihat:
class PizzaStore:
...
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.
The tracebacks are present on the __traceback__
attribute of the errors
returned when calling send_robust()
.
Memutus sambungan sinyal¶
To disconnect a receiver from a signal, call Signal.disconnect()
. The
arguments are as described in Signal.connect()
. The method returns
True
if a receiver was disconnected and False
if not.
Argumen receiver
menunjukkan penerima terdaftar untuk tidak terhubung. Itu mungkin None
jika dispatch_uid
digunakan untuk mencirikan penerima.