Django’s semaphores

A, aboutdjangoA semaphoreWebsite unit

Django includes a “signal scheduler,” which helps inform separate applications when actions occur elsewhere in the framework. In short, signals allow certain senders to notify a group of receivers that certain actions have taken place. They are especially useful when many pieces of code might be interested in the same event.

Second,djangoA semaphore built into the

  • 1. Semaphore of Model

    • Pre_init # This is triggered automatically before Djangos modal executes its constructor

    • Post_init # Django automatically fires when its constructor is executed in Modal

    • Pre_save # Automatically triggered before Djangos modal objects are saved

    • Post_save # Djangos modal objects are automatically triggered when saved

    • Pre_delete # Automatically triggered before a Django Modal object is deleted

    • Post_delete # Django automatically triggers deletion of modal objects

    • M2m_changed # Automatically triggered when the third table (add,remove,clear) is operated with the M2M field in Django modal

    • When the class_prepared program starts, it detects the modal classes in the registered app and automatically fires for each class

      from django.db.models.signals import class_prepared
      from django.db.models.signals import pre_init
      from django.db.models.signals import post_init
      from django.db.models.signals import pre_save
      from django.db.models.signals import post_save
      from django.db.models.signals import pre_delete
      from django.db.models.signals import post_delete
      from django.db.models.signals import m2m_changed
      Copy the code
  • 2. Management semaphores

    • Pre_migrate # This command is automatically triggered before the migrate command is executed

    • Post_migrate # This command is automatically triggered after the migrate command is executed

      from django.db.models.signals import pre_migrate
      from django.db.models.signals import post_migrate
      Copy the code
  • 3. Request/Response semaphore

    • Request_started # Automatically triggers the request before it arrives

    • Request_finished # Automatically triggered after the request ends

    • Got_request_exception # Automatically triggered when a request is abnormal

      from django.core.signals import request_finished
      from django.core.signals import request_started
      from django.core.signals import got_request_exception
      Copy the code
  • 4. Semaphore of Test

    • Setting_changed # Triggered automatically when a configuration file is modified using test

    • Template_rendered # Automatically triggered when a rendered template is tested using test

      from django.test.signals import setting_changed
      from django.test.signals import template_rendered
      Copy the code
  • 5. Database semaphore

    • Connection_created # Automatically triggered when a database connection is created

      from django.db.backends.signals import connection_created
      Copy the code

Third, indjangoThe use ofconnectDefining semaphore

  • 1. Official website cases

    To receive signals, use this method to register the receiver function signal.connect (). The receiver function is called when a signal is sent.

    Signal. Connect (receiver, sender = None, weak = True, dispatch_uid = None)

    • receiver– The callback function that will connect to this signal. See Receiver features for more information.
    • sender– Specifies the specific sender from which the signal is received. For more information, see Connecting to Signals sent by a specific sender.
    • weakDjangoSignal handlers are stored as weak references by default. Therefore, if your receiver is a native function, it may be garbage collection. To prevent this, pleaseweak=FalseCalling signalconnect()Method is passed.
    • dispatch_uid– Unique identifier of the signal receiver in cases where duplicate signals may be sent. For more information, see Preventing Duplicate Signals.
  • 2, define a signal before and after the database save (defined in the project’s __init__.py file)

    from django.db.models import signals
    
    def before_save(*args, **kwargs):
        """ Define a signal that fires before saving data :param args: :param kwargs: :return: ""
        print('=== data saved before triggering ===')
        print(args, kwargs)
        print('=== data saved before triggering ===')
    
    def post_save(*args, **kwargs):
        """ Defines a signal that is triggered after the data is saved :param args: :param kwargs: :return: ""
        print('== triggered after data save ==')
        print(args, kwargs)
        print('== triggered after data save ==')
    
    signals.pre_save.connect(before_save)
    signals.post_save.connect(post_save)
    Copy the code
  • 3, test,

Four, the use ofreceiverDecorators define semaphores

  • 1. Also in the __init__.py file of the project

  • 2, guide package

    from django.core.signals import request_finished
    from django.dispatch import receiver
    Copy the code
  • 3. Define semaphore functions

    @receiver(request_finished)
    def my_callback(sender, **kwargs):
        print(The '-' * 100)
        print(sender, kwargs)
        print("Request finished!")
    Copy the code

Not specifying the receiver is global, usually written directly in the project__init__.pyIn the file, if is only for the individualappNot globally configured

5, About specifying receiver (component semaphore)

  • 1. Create a messs.py file in the component

  • 2, messs.py specifies the receiver of the signal

    from django.db.models import signals
    from app01.models import ClassModel, StudentModle
    
    def before_save(*args, **kwargs):
        """ Define a signal that fires before saving data :param args: :param kwargs: :return: ""
        print('=== data saved before triggering ===')
        print(args, kwargs)
        print('=== data saved before triggering ===')
    
    signals.pre_save.connect(before_save, sender=ClassModel)
    Copy the code
  • 3. If it is the way of using decorators

    from django.core.signals import request_finished
    from django.dispatch import receiver
    from .views import app02Test
    
    @receiver(request_finished, sender=app02Test)
    def my_callback(sender, **kwargs):
        print(The '-' * 100)
        print(sender, kwargs)
        print("Request finished!")
    Copy the code

6. Custom signal

  • Create a file in your app

  • 2. Customize signals in the file

    # Define signal
    import django.dispatch
    
    pizza_done = django.dispatch.Signal(providing_args=["toppings"."size"])
    
    # register signal
    def callback(sender, **kwargs):
        print("callback")
        print(sender, kwargs)
    
    pizza_done.connect(callback)
    Copy the code
  • 3. Send signals in the view

    fromThe fileimport pizza_done
    pizza_done.send(sender='seven', toppings=123, size=456)
    Copy the code