码迷,mamicode.com
首页 > 其他好文 > 详细

django(12)、信号

时间:2018-08-09 14:04:13      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:基类   red   ssi   providing   app   tar   发送   ret   后台   

内置信号

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,update),自动触发
class_prepared    # 程序启动时,检测到已注册的model类,对于每一个类,自动触发
request_started     # 请求到来前,自动触发
request_finished    # 请求结束后,自动触发
got_request_exception           # 请求异常时,自动触发
setting_changed     # 配置文件改变时,自动触发
template_rendered   # 模板执行渲染操作时,自动触发
connection_created  # 创建数据库连接时,自动触发

内置信号使用:以pre_savepost_save为例,

# 项目目录 init.py

# 1、导入需要引用的内置信号
from django.db.models.signals import pre_save, post_save 


# 2、自定义功能函数
def pre_save_func(sender, **kwargs):
    print('pre_save_fun')
    print('pre_save_msg:', sender, kwargs)


def post_save_func(sender, **kwargs):
    print('post_save_func')
    print('post_save_msg:', sender,kwargs)


# 3、绑定功能函数到信号
pre_save.connect(pre_save_func)  # 在save对象前触发
post_save.connect(post_save_func)  # 在save对象后触发



# 4、打印结果
pre_save_fun
pre_save_msg: <class 'app01.models.Author'> {'signal': <django.db.models.signals.ModelSignal object at 0x0343F990>, 'instance': <Author: kate>, 'raw': False, 'using': 'default', 'update_fields': None}
post_save_func
post_save_msg: <class 'app01.models.Author'> {'signal': <django.db.models.signals.ModelSignal object at 0x0343F9F0>, 'instance': <Author: kate>, 'created': True, 'update_fields': None, 'raw': False, 'using': 'default'}

自定义信号

  • 1、创建文件, 定义信号:

    # /utils/signal_test.py
    # step1:实例化signal对象
    import django.dispatch
    action=django.dispatch.Signal(providing_args=["aaa","bbb"])
  • 2、在项目应用的init文件中完成功能函数和绑定信号

    # django_review\__init__.py
    from utils.signal_test import action
    
    # step2:定义receiver(A function or an instance method which is to receive signals.)
    def pre_save_func(sender, **kwargs):
        print("pre_save_func")
        print("pre_save_msg:", sender, kwargs)
    
    # step3:Connect receiver to sender for signal.
    action.connect(pre_save_func)
  • 3、在视图函数中触发信号

    from utils.signal_test import action
    
    
    def index(request):
        books = Book.objects.all()
        author = Author.objects.create(name='kate1',gender=1)
    
        # step4:发送信号到所有连接的reciever(Send signal from sender to all connected receivers.)
        action.send(sender='create', aaa=author.name, bbb=author.get_gender_display())
        return render(request, 'index.html', locals())
  • 4、结果展示

    pre_save_func
    pre_save_msg: create {'signal': <django.dispatch.dispatcher.Signal object at 0x04287370>, 'aaa': 'kate1', 'bbb': '女'}
    [09/Aug/2018 11:00:50] "GET / HTTP/1.1" 200 990

信号和中间件的区别

  • 信号比中间件散布的范围更广。
  • 在后台的许多动作事件都可以触发内置的信号,从而执行与之绑定的函数
  • 也可以自定义信号扩展其功能
  • 而中间件常用的就只有四个函数,且仅在接受请求和返回请求的过程中起作用

源码分析

class Signal(object):
    """所有信号的基类"""
    
    def __init__(self, providing_args=None, use_caching=False):

        self.receivers = []
        if providing_args is None:
            providing_args = []
        self.providing_args = set(providing_args)

    def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
         """
        Connect receiver to sender for signal.
        
        Arguments:
            receiver
                A function or an instance method which is to receive signals.
                Receivers must be hashable objects.
        """
        pass

    def send(self, sender, **named):
        """
        Send signal from sender to all connected receivers.

        If any receiver raises an error, the error propagates back through send,
        terminating the dispatch loop. So it's possible that all receivers
        won't be called if an error is raised.

        Arguments:
            sender
                The sender of the signal. Either a specific object or None.

            named
                Named arguments which will be passed to receivers.
        Returns a list of tuple pairs [(receiver, response), ... ].
        """
        pass

django(12)、信号

标签:基类   red   ssi   providing   app   tar   发送   ret   后台   

原文地址:https://www.cnblogs.com/fqh202/p/9448056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!