Django中提供了‘信号调度‘,用于在框架执行操作时解耦。
通俗来讲,就是一些动作发生时,信号允许特定的发送者去提醒一些接受者。
Django内置信号
Model signals pre_init # django的model执行其构造方法前,自动触发 post_init # django的model执行其构造方法后,自动触发 pre_save # django的model对象保存前,自动触发 post_save # django的model对象保存后,自动触发 pre_delete # django的model对象删除前,自动触发 post_delete # django的model对象删除后,自动触发 m2m_changed # django的model中使用m2m字段操作第三张表(add,remove,clear)前后,自动触发 class_prepared # 程序启动时,检测已注册的app中model类,对于每一个类,自动触发 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 # 创建数据库连接时,自动触发
对于Django内置的信号,仅需注册指定信号,当程序执行相应操作时,自动触发注册函数。
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 callback(sender, **kwargs): print("xxoo_callback") print(sender,kwargs) xxoo.connect(callback) # xxoo指上述导入的内容
from django.core.signals import request_finished from django.dispatch import receiver @receiver(request_finished) def my_callback(sender, **kwargs): print("Request finished!")
例子:
例子,创建数据库记录,触发pre_save和post_save信号 创建一个Django项目,配置好路由映射 models.py中的代码: from django.db import models class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=64) views.py中的代码: from django.shortcuts import render,HttpResponse from app01 import models def index(request): models.UserInfo.objects.create(name="mysql",pwd="mysql123") return HttpResponse("ok") 项目的__init__.py文件中代码: from django.db.models.signals import pre_save,post_save def pre_save_func(sender,**kwargs): print("pre_save_func") print("pre_save_msg:",sender,kwargs) def post_save_func(sender,**kwargs): print("post_save_func") print("post_save_msg:",sender,kwargs) pre_save.connect(pre_save_func) # models对象保存前触发callback函数 post_save.connect(post_save_func) # models对象保存后触发函数 创建一个index.html网页,用浏览器打开这个项目,在服务端后台打印信息如下: pre_save_func pre_save_msg: <class ‘app01.models.UserInfo‘> {‘signal‘: <django.db.models.signals.ModelSignal object at 0x0000000002E62588>, ‘instance‘: <UserInfo: UserInfo object>, ‘raw‘: False, ‘using‘: ‘default‘, ‘update_fields‘: None} post_save_func post_save_msg: <class ‘app01.models.UserInfo‘> {‘signal‘: <django.db.models.signals.ModelSignal object at 0x0000000002E62630>, ‘instance‘: <UserInfo: UserInfo object>, ‘created‘: True, ‘update_fields‘: None, ‘raw‘: False, ‘using‘: ‘default‘} 比较打印的结果,可以看到models对象保存后,在打印信息里包含一个"create=True"的键值对. 也可以使用装饰器来触发信号,把上面__init__.py中的代码修改: from django.core.signals import request_finished from django.dispatch import receiver @receiver(request_finished) def callback(sender, **kwargs): print("Request finished!") 则在本次请求结束后自动触发callback函数,在后台"request finished"这句话.
信号示例
自定义信号
1.定义信号
新建一个项目,配置好路由,在项目根目录下创建一个singal_test.py
的文件,内容为
import django.dispatch action=django.dispatch.Signal(providing_args=["aaaa","bbbb"])
2.注册信号
项目应用下面的__init__.py
文件内容:
from singal_test import action def pre_save_func(sender,**kwargs): print("pre_save_func") print("pre_save_msg:",sender,kwargs) action.connect(pre_save_func)
3.触发信号
views视图函数内容:
from singal_test import action action.send(sender="python",aaa="111",bbb="222") 用浏览器打开index.html网页,后台打印信息如下: pre_save_func pre_save_msg: python {‘signal‘: <django.dispatch.dispatcher.Signal object at 0x000000000391D710>, ‘aaa‘: ‘111‘, ‘bbb‘: ‘222‘}
由于内置信号的触发者已经集成到Django中,所以会自动调用,而对于自定义信号需要在任意位置触发
自定义信号示例2:
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) # 触发信号 pizza_done.send(sender=‘seven‘,toppings=123, size=456)
示例2
原文地址:https://www.cnblogs.com/ugfly/p/8387310.html
时间: 2024-10-13 23:48:52