曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
Django

Getting Started with Django's Signal Mechanism

Concepts Django comes with a built-in signal mechanism to help us pass information between different parts of the framework. That is, when a certain event occurs, the signal system allows one or more senders to send notifications or signals to a group of receivers. (It feels a lot like Qt's signals and slots mechanism) The signal system consists of the following three elements: Sender – the party that emits the signal Signal – the signal itself Receiver – the recipient of the signal Django has a built-in set of signals; here are some of the more commonly used ones: When

曦远 (DealiAxy)约 12 分钟
目录12 个章节

Concepts

Django comes with a built-in signal mechanism to help us pass information between different parts of the framework. That is, when a certain event occurs, the signal system allows one or more senders to send notifications or signals to a group of receivers.

(It feels a lot like Qt's signals and slots mechanism)

The signal system consists of the following three elements:

  • Sender – the party that emits the signal
  • Signal – the signal itself
  • Receiver – the recipient of the signal

Django has a built-in set of signals; here are some of the more commonly used ones:

Signals sent before or after the ORM model's save() method is called

django.db.models.signals.pre_save
django.db.models.signals.post_save

Signals sent before or after the delete() method of an ORM model or queryset is called.

django.db.models.signals.pre_delete
django.db.models.signals.post_delete

Signals sent when a many-to-many field is modified.

django.db.models.signals.m2m_changed

Signals sent when an HTTP request is received and when it is finished.

django.core.signals.request_started
django.core.signals.request_finished

This is quite convenient. Imagine a scenario where we introduce a third-party Django library that creates models, and we want to modify data in other tables at the same time it creates models, without modifying its code. That's when the signal mechanism comes in handy.

Simple Usage Example

There are two ways to listen for signals: one is the Signal.connect() method, and the other is a decorator.

The Signal.connect() Method

Method prototype:

Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None)[source]

Parameters:

  • receiver: The callback function connected to the current signal, i.e., the function that handles the signal.
  • sender: Specifies which sender to receive signals from.
  • weak: Whether to use a weak reference
  • dispatch_uid: A unique identifier for the signal receiver, to prevent the signal from being sent multiple times.

Decorator Approach

from django.core.signals import request_finished
from django.dispatch import receiver

@receiver(request_finished)
def my_callback(sender, **kwargs):
    print("Request finished!")

You can add a sender parameter to receiver to filter which model's signals to receive, for example:

from django.db.models import signals
from django.dispatch import receiver

@receiver(signals.post_save, sender=MyModel)
def demo_callback(sender: MyModel, instance: MyModel, **kwargs):
    pass

Note that to read the passed-in model object you must use the instance parameter, not sender! sender is a type!

Setting the dispatch_uid Parameter to Prevent Duplicate Signals

To prevent duplicate signals, you can set the dispatch_uid parameter to identify your receiver. The identifier is usually a string, as shown below:

from django.core.signals import request_finished

request_finished.connect(my_callback, dispatch_uid="my_unique_identifier")

Disconnecting Signals

When certain conditions are met and we no longer need to listen for signals, we can choose to disconnect them.

Signal.disconnect() is used to disconnect a signal's receiver. The parameters are the same as those in Signal.connect(). If the receiver is successfully disconnected, it returns True; otherwise it returns False.

Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)[source]

Afterword

I recently started a new job and have been especially busy with many projects, and I've also learned a lot of new technologies. But I feel like I haven't had time to properly write a blog post in a long time. Even this article was pieced together in a short time—it's really tough. I need to properly organize my recent technical notes over the weekend.

For more on Django's signal mechanism (custom signals, etc.), you can refer to the official documentation. https://docs.djangoproject.com/en/3.0/topics/signals/

PS: Next I should write about research related to Django Admin solutions, emm, and also about WeChat Mini Program login and payment integration. They're not particularly hard, but if it's your first time using them, there are pitfalls everywhere...

Welcome to Discuss

I've compiled a series of technical articles and materials. Reply with linux, flutter, c#, netcore, android, java, python, etc. in the backend of the WeChat official account "Programming Lab" to get related technical articles and materials. Feel free to leave a message in the official account backend if you have any questions~

_EOF_

Getting Started with Django's Signal Mechanism

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

一小时完成后台开发:DjangoRestFramework开发实践

DjangoRestFramework开发实践 在这之前我写过一篇关于Django与Drf快速开发实践的博客,Django快速开发实践:Drf框架和xadmin配置指北,粗略说了一下Drf配置和基本使用,不过里面只是涉及到最基本的CRUD,在正常的后端开发中涉及的诸如认证和权限、消息队列、缓存之类的操作,上一篇博客并没有涉及,这次开发我仔细了看了官方文档的这几个部分,把这部分的功能完善了起来。 D

2021-12-18 · Django · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…