Pieces pieces pieces

Basic introduction

Django has custom singals that listen for actions and send notifications.

Django provides a "signal distributor" that allows decoupled applications to be notified when actions occur elsewhere in the framework.

In simple terms, signals allow a particular sender to notify a set of Receivers that some operation has occurred. This is useful in cases where multiple pieces of code are associated with the same event.

Django has built-in some singals in django/db/models/signal py, such as

Model signalsPre_init # This is triggered automatically before Djangos modal executes its constructorPost_init # Django automatically fires when its constructor is executed in ModalPre_save # Automatically triggered before Djangos modal objects are savedPost_save # Djangos modal objects are automatically triggered when savedPre_delete # Automatically triggered before a Django Modal object is deletedPost_delete # Django automatically triggers deletion of modal objectsM2m_changed # Automatically triggered when the third table (add,remove,clear) is operated with the M2M field in Django modalWhen the class_prepared program starts, it detects the modal classes in the registered app and automatically fires for each classManagement signalsPre_migrate # This command is automatically triggered before the migrate command is executedPost_migrate # This command is automatically triggered after the migrate command is executedRequest/response signalsRequest_started # Automatically triggers the request before it arrivesRequest_finished # Automatically triggered after the request endsGot_request_exception # Automatically triggered when a request is abnormalTest signalsSetting_changed # Triggered automatically when a configuration file is modified using testTemplate_rendered # Automatically triggered when a rendered template is tested using testDatabase WrappersConnection_created # Automatically triggered when a database connection is createdCopy the code

Pieces pieces pieces

How to use

These singals can be used to achieve some linkage operations in the application

  • To change the logging of the operator when updating through the Model, you can either use the Post_save decorator directly where the action was taken, or rewrite post_SAVE to record the information once and for all

  • When a request is made, the request information is recorded

from django.core.signals import request_finishedfrom django.dispatch import receiver@receiver(request_finished)def my_callback(sender, **kwargs):print("Request finished!" )Copy the code

Custom Singals

A. Define the signalimport django.dispatchpizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])B. Registration signaldef callback(sender, **kwargs):    print("callback")    print(sender,kwargs)    pizza_done.connect(callback)C. Trigger signalFrom path import pizza_donepizza_done.send(sender='seven',toppings=123, size=456)Copy the code

Pieces pieces pieces

Usage scenarios

There is a requirement in the project, when model(i.e. library data) is modified or deleted, automatically trigger a redis synchronization task, model save has post_save, delete has post_delete, but not update, and the code uses update scenarios quite a lot. I searched why there was no update singals.

Related: https://code.djangoproject.com/ticket/12184

The latest django release, version 1.9, does not support this option. You have to write a new django application and remove it if there are any problems.

Specific writing:

Singals. Py files------------------- Custom Singal ---------------# coding:utf-8from django.dispatch import Signalpost_update = Signal(providing_args=["user"])Models. Py files-- -- -- -- -- -- -- -- -- -- - for a model, rewrite the update in the queryset methods -- -- -- -- -- -- -- -- -- -- -// Import a custom signal filefrom tools  import signals class MyCustomQuerySet(models.query.QuerySet):    def update(self, **kwargs):        super(MyCustomQuerySet, self).update(**kwargs)// Send singalsignals when update is called        signals.post_update.send(sender=self.model, user="xxx")print("finished!" )class MyCustomManager(models.Manager):    def get_queryset(self):        return MyCustomQuerySet(self.model, using=self._db)class crontab_ping(models.Model):    name = models.CharField(max_length=64, blank=True, null=True)    objects = MyCustomManager()The callback. Py files:------- Receives signal and triggers an operation ----------from tools.signals import post_update@receiver(post_update)def post_update_callback(sender, **kwargs):    print(kwargs['user'])    print("post_update_success")Copy the code

Long press to identify

Focus on technology 90