django-信号
django在ORM操作之前或之后,可以通过信号定制一些其他操作。
project下init.py
from django.db.models import signals def before_save1(*args,**kwargs): print('数据库插入数据之前',args,kwargs) def before_save2(*args,**kwargs): print('数据库插入数据之前2',args,kwargs) def after_save1(*args,**kwargs): print('数据库插入数据之后',args,kwargs) signals.pre_save.connect(before_save1) signals.pre_save.connect(before_save2) signals.post_save.connect(after_save1)
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-根目录新建py文件(sg.py) 导入内置信号 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) pre_save.connect(f1) 2-init.py导入 import sg 3-试图函数执行相应数据库操作时自动执行信号 def signal(reuqest): from app01 import models obj = models.UserInf(user='root') print('end') obj.save() 二、自定义信号 a-定义信号--sg.py中 import django.dispatch pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"]) 名称自行设置--pizza_done b-注册信号--sg.py中 def callback(sender, **kwargs): print("callback") print(sender,kwargs) pizza_done.connect(callback) c-触发信号 视图函数中 def signal(reuqest): from sg import pizza_done pizza_done.send(sender="asdfasdf", toppings=123, size=456) 参数任意值均可