Django里面还提供了一个功能叫做信号。信号类似触发器,可以指定在某个事件发生前后自动执行对应的函数。
Django自带了一些信号,如下所示:
Model signals pre_init # django的modal执行其构造方法前,自动触发 post_init # django的modal执行其构造方法后,自动触发 pre_save # django的modal对象保存前,自动触发 post_save # django的modal对象保存后,自动触发 pre_delete # django的modal对象删除前,自动触发 post_delete # django的modal对象删除后,自动触发 m2m_changed # django的modal中使用m2m字段操作第三张表(add,remove,clear)前后,自动触发 class_prepared # 程序启动时,检测已注册的app中modal类,对于每一个类,自动触发 Management signals pre_migrate # 执行migrate命令前,自动触发 post_migrate # 执行migrate命令后,自动触发 Request/response signals request_started # 请求到来前,自动触发 request_finished # 请求结束后,自动触发 got_request_exception # 请求异常后,自动触发 Test signals setting_changed # 使用test测试修改配置文件时,自动触发 template_rendered # 使用test测试渲染模板时,自动触发 Database Wrappers connection_created # 创建数据库连接时,自动触发
如果需要使用的话,只需要导入对应的类,然后自己创建一个函数,再把自己的函数绑定到对应的信号就会自动执行了(这个过程叫做注册信号)。
例1:
创建一个sg.py,可以看见注册信号有2种方式写都是可以的,f1和f2用的第一种;f3用的第二种
from django.core.signals import request_finished from django.core.signals import request_started from django.core.signals import got_request_exception from django.db.models.signals import class_prepared from django.db.models.signals import pre_init, post_init from django.db.models.signals import pre_save, post_save from django.db.models.signals import pre_delete, post_delete from django.db.models.signals import m2m_changed from django.db.models.signals import pre_migrate, post_migrate from django.test.signals import setting_changed from django.test.signals import template_rendered from django.db.backends.signals import connection_created def f1(sender, **kwargs): print("xxoo_callback") # print(sender,kwargs) def f2(sender, **kwargs): print("Do something before request") print("--------------------------") #注册信号方法1 pre_save.connect(f1) request_started.connect(f2) #注册信号方法2 from django.dispatch import receiver @receiver(request_finished) def f3(sender,**kwargs): print("--------------------------") print("Do something after request") #自定义一个信号叫做pizza_done,要求提供两个参数 import django.dispatch pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"]) #下面步骤一样的,注册信号,绑定回调函数 def callback(sender, **kwargs): print("callback") print(sender,kwargs) pizza_done.connect(callback)
Views.py
自己写的一个视图函数
def signal(reuqest): from app01 import models obj = models.UserInf(user=‘root‘) obj.save() obj = models.UserInf(user=‘root‘) obj.save() obj = models.UserInf(user=‘root‘) obj.save() from sg import pizza_done pizza_done.send(sender="asdfasdf",toppings=123, size=456)
执行结果,在获取request之前,触发了f2,然后每次保存数据都触发了f1,然后通过send触发了一个自定义的信号,完成request之后,触发了f3
Do something before request -------------------------- xxoo_callback xxoo_callback xxoo_callback callback asdfasdf {‘signal‘: <django.dispatch.dispatcher.Signal object at 0x03342FF0>, ‘toppings‘: 123, ‘size‘: 456} [07/Sep/2017 16:29:16] "GET /signal/ HTTP/1.1" 200 2 -------------------------- Do something after request
本文出自 “麻婆豆腐” 博客,请务必保留此出处http://beanxyz.blog.51cto.com/5570417/1963402
原文地址:http://beanxyz.blog.51cto.com/5570417/1963402