Django的信号功能怎样使用?下面我将通过实例来给大家介绍。
有如下场景, 我有一个Model名为Alert,表示一条告警. 我需要在创建一个告警后进行邮件通知. 怎么实现呢?
Alert类加一个表示字段is_notify表示是否通知过. 然后创建一个command,在后台定时读取Alert里未通知的记录:
1 2 3 4 |
for alert in Alert.objects.filter(is_notify = False): # 发邮件 alert.is_notify = True |
这种方式有如下缺点:
下面看一下使用django 信号实现上面的功能:
1 2 3 4 5 6 |
@receiver(post_save, sender=Alert) def alert_notify(sender, instance, created, **kwargs): if not created: return # 发送邮件 |
有没有觉得很简单呢, 只需要监听django的信号就可以知道所关心的对象的创建,然后做想做的事.
比如我这里有一个django app名为app
default_app_config = ‘app.apps.AppConfig’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from __future__ import unicode_literals import os from django.apps import AppConfig class AppConfig(AppConfig): name = 'app' def ready(self): # registers some single import app.signals <ul> <li>app/signals.py</li> </ul> @receiver(post_save, sender=Alert) def alert_notify(sender, instance, created, **kwargs): if not created: return # 发送邮件 |
使用Django信号不进可以实现一些高级功能,还能很好的解耦代码.
Django里有很多信号,下面列举一些
如果信号不满足要求,还可以自定义信号. 详细可以看看官方文档