django中实现观察者模式

在Django中实现观察者模式,你可以利用Django的信号(Signals)系统。Django的信号提供了一种发布/订阅模型,允许解耦应用程序组件之间的交互。一个组件可以发送一个信号,而其他组件可以监听这个信号并响应它。

下面是如何在Django中使用信号来实现观察者模式的一个例子:

一:定义

首先,你需要定义你的信号。这通常在一个signals.py文件中完成。

signals.py

from django.dispatch import Signal

定义一个信号

my_signal = Signal(providing_args=["some_arg", "another_arg"])

然后,在其他应用中,你可以发送这个信号。

some_app/models.py

from .signals import my_signal

发送信号

def some_function_that_sends_signal(some_arg, another_arg):

my_signal.send(sender=None, some_arg=some_arg, another_arg=another_arg)

在其他地方,你可以接收并响应这个信号。这通常在ready()方法中完成,该方法在Django的应用启动时执行。

another_app/apps.py

from django.apps import AppConfig

from . import receivers

class AnotherAppConfig(AppConfig):

name = 'another_app'

def ready(self):

导入信号接收函数以注册它们

from .receivers import my_signal_receiver

连接信号和接收函数

my_signal.connect(my_signal_receiver)

another_app/receivers.py

from . import models

def my_signal_receiver(sender, some_arg, another_arg, **kwargs):

接收信号并执行一些操作

print(f"Signal received with some_arg: {some_arg} and another_arg: {another_arg}")

例如,你可以在数据库中创建或更新记录

models.SomeModel.objects.create(field1=some_arg, field2=another_arg)

在这个例子中,my_signal_receiver是一个信号接收函数,它会在my_signal信号被发送时调用。some_function_that_sends_signal是发送信号的地方,而AnotherAppConfig.ready()方法则是确保信号接收函数在Django启动时就被连接到信号上。

这样,当你调用some_function_that_sends_signal时,所有连接到my_signal的接收函数都会被调用,实现了观察者模式中的通知机制。

相关推荐
喵手24 分钟前
Python爬虫实战:电商问答语料构建完整实战 - 从爬取到检索语料的工程化实现(附CSV导出 + SQLite持久化存储)!
爬虫·python·sqlite·爬虫实战·零基础python爬虫教学·电商问答语料构建·爬取到检索语料
APIshop1 小时前
淘宝商品评论接口实战解析:从抓包到数据抓取全链路技术指南
java·python
~央千澈~1 小时前
抖音弹幕游戏开发之第14集:添加更多整蛊效果·优雅草云桧·卓伊凡
开发语言·python·游戏
多打代码2 小时前
2026.02.11
开发语言·python
AI周红伟3 小时前
周红伟:智能体实战,通过使用 Flask 的 REST API 在 Python 中部署 PyTorch
后端·python·flask
清水白石0083 小时前
Python 性能分析实战指南:timeit、cProfile、line_profiler 从入门到精通
开发语言·python
ValhallaCoder3 小时前
hot100-二分查找
数据结构·python·算法·二分查找
Suryxin.3 小时前
从0开始复现nano-vllm「llm_engine.py」
人工智能·python·深度学习·ai·vllm
PieroPc3 小时前
用python 写的 Gitee 数据备份工具
开发语言·python·gitee
电饭叔3 小时前
intVar 说明
python