Signals
信号:在需要的地方通知receiver某些操作已发生。如调用model的save方法时会发送pre_save(在调用save之前)和post_save,pre_save可以连接一个receiver函数,在函数中做需要的处理。
两种方式接收信号
1.使用connect
from django.core.signals import request_finished #request_finished是内置信号 request_finished.connect(my_callback)
2.使用装饰器
from django.core.signals import request_finished from django.dispatch import receiver @receiver(request_finished) def my_callback(sender, **kwargs): print("Request finished!")
对信号使用connect,对receiver使用装饰器
自定义信号
import django.dispatch pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
#providing_args为发送信号是需要携带的参数
发送信号
Signal.send(sender, **kwargs)[source] 或者
Signal.send_robust(sender, **kwargs)[source]
两者都有返回值:
Bothsend()
andsend_robust()
return a list of tuple pairs[(receiver, response), ... ]
, representing the list of called receiver functions and their response values.
区别:
send不捕获异常,出现异常不保证能通知到所有receiver,send_robust捕获异常,出现异常可以通知所有receiver,异常会在返回的tuple中
要有一个sender,空字符串也行