返回文章列表文章索引阅读全文
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 许可协议。转载请注明出处!

相关文章

Django全文检索实现:HayStack-+-Whoosh-+-Jieba

涉及到的工具 haystack是django的开源搜索框架,该框架支持**Solr**, Elasticsearch, Whoosh, **Xapian搜索引擎,不用更改代码,直接切换引擎,减少代码量。 搜索引擎使用Whoosh,这是一个由纯Python实现的全文搜索引擎,没有二进制文件等,比较小巧,配置比较简单,当然性能自然略低。 中文分词Jieba,由于Whoosh自带的是英文分词,对中文的分

2022-08-26 · Django · 约 1 分钟

配置Django-TinyMCE组件支持上传图片功能

Django自带的Admin后台,好用,TinyMCE作为富文本编辑器,也蛮好用的,这两者结合起来在做博客的时候很方便(当然博客可能更适合用Markdown来写),但是Django-TinyMCE这个组件默认没有图片上传功能的,需要我们自己实现,本文将一步步带大家实现这个图片上传功能。 读者也可以举一反三实现其他需要和Django结合的功能。 编写上传图片逻辑 在任一views.py里添加代码:

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

讨论

共 0 条

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

加载评论中…