django signal

date
Jun 13, 2021
slug
45
status
Published
tags
Backend
Django
summary
type
Post

Django Signals 信号

入门

# receiver 接收者
# sender是必选参数
def my_callback(sender, **kwargs):
    print sender
    print kwargs
    print("Request finished!")
# 关联信号和接受者
# 但是连接的时候 sender可以是None, 一种特殊类型的sender, 表示不在意发送者类型(其实就是默认类型).
from django.core.signals import request_finished
request_finished.connect(my_callback)
# 另一种关联方式
@receiver(request_finished)
def my_callback(sender, **kwargs):
# **kwargs 和 sender 中的 **kwargs 对应    
	pass
# 信号定义
request_finished = Signal()
# 发送信号
# sender必选, 可以是None
request_finished.send(sender=***,**kwargs)
# 断开信号
Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)

connect

sender 可以是任意类型
  • None – 任意发送者都可以
  • 对象,字符串,都可以. 只要可以hash
 
weak receiver在signal对象中被维护成一个弱引用列表. 如果receiver是一个局部变量, 这个receiver就丢了. 如果weak是false. 可以避免这个情况.
dispatch_uid 绑定多次会出问题,此id可以避免绑定多次的情况. 譬如,绑定两次,self.receivers 就会出现两次,那么receiver就会被调用两次.
# Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None)

@receiver(pre_save, sender=MyModel, weak=True, dispatch_uid=None)
def my_handler(sender, **kwargs):
    '''The my_handler function will only be called when an instance of MyModel is saved'''

© chaleaoch 2021