通知是任何现代 Web 应用程序的关键组成部分,可确保用户了解情况并参与其中。实施良好的通知系统可以处理多个渠道,例如应用内警报、电子邮件和短信,同时动态定制内容以实现无缝的用户体验。在本指南中,我们将引导您在 Django 中创建一个强大的、可扩展的通知系统。
我们的通知系统旨在提供:
模板是我们系统的支柱,存储可重复使用的通知内容。
from django.db import models class ChannelType(models.TextChoices): APP = 'APP', 'In-App Notification' SMS = 'SMS', 'SMS' EMAIL = 'EMAIL', 'Email' class TriggeredByType(models.TextChoices): SYSTEM = 'SYSTEM', 'System Notification' ADMIN = 'ADMIN', 'Admin Notification' class TriggerEvent(models.TextChoices): ENROLLMENT = 'ENROLLMENT', 'Enrollment' ANNOUNCEMENT = 'ANNOUNCEMENT', 'Announcement' PROMOTIONAL = 'PROMOTIONAL', 'Promotional' RESET_PASSWORD = 'RESET_PASSWORD', 'Reset Password' class NotificationTemplate(models.Model): title = models.CharField(max_length=255) template = models.TextField(help_text='Use placeholders like {{username}} for personalization.') channel = models.CharField(max_length=20, choices=ChannelType.choices, default=ChannelType.APP) triggered_by = models.CharField(max_length=20, choices=TriggeredByType.choices, default=TriggeredByType.SYSTEM) trigger_event = models.CharField(max_length=50, choices=TriggerEvent.choices, help_text='Event that triggers this template.') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
主要特点:
通知模型将模板链接到用户并存储任何动态负载以进行个性化。
class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="notifications") content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name="notifications") payload = models.JSONField(default=dict, help_text="Data to replace template placeholders.") is_read = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True)
为了独特地处理电子邮件和短信,我们定义了特定的模型。
电子邮件通知
该模型管理特定于电子邮件的数据,例如动态消息生成和传递跟踪。
class StatusType(models.TextChoices): PENDING = 'PENDING', 'Pending' SUCCESS = 'SUCCESS', 'Success' FAILED = 'FAILED', 'Failed' class EmailNotification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='email_notifications') content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name='email_notifications') payload = models.JSONField(default=dict) status = models.CharField(max_length=20, choices=StatusType.choices, default=StatusType.PENDING) status_reason = models.TextField(null=True) @property def email_content(self): """ Populate the template with dynamic data from the payload. """ content = self.content.template for key, value in self.payload.items(): content = re.sub( rf"{{{{\s*{key}\s*}}}}", str(value), content, ) return content
短信通知
与电子邮件通知类似,这里实现了短信特定逻辑。
class SMSNotification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sms_notifications') content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name='sms_notifications') payload = models.JSONField(default=dict) status = models.CharField(max_length=20, choices=StatusType.choices, default=StatusType.PENDING) status_reason = models.TextField(null=True) @property def sms_content(self): """ Populate the template with dynamic data from the payload. """ content = self.content.template for key, value in self.payload.items(): content = re.sub( rf"{{{{\s*{key}\s*}}}}", str(value), content, ) return content
为了更轻松地管理通知,我们在 Django 管理面板中注册模型。
from django.contrib import admin from notifier.models import NotificationTemplate @admin.register(NotificationTemplate) class NotificationTemplateAdmin(admin.ModelAdmin): list_display = ['title', 'channel', 'triggered_by', 'trigger_event', 'is_active'] list_filter = ['channel', 'triggered_by', 'is_active'] search_fields = ['title', 'trigger_event']
我们将实现一个服务层来管理通过各种渠道发送通知。
使用策略模式,我们将为每个通知通道定义类。
from django.db import models class ChannelType(models.TextChoices): APP = 'APP', 'In-App Notification' SMS = 'SMS', 'SMS' EMAIL = 'EMAIL', 'Email' class TriggeredByType(models.TextChoices): SYSTEM = 'SYSTEM', 'System Notification' ADMIN = 'ADMIN', 'Admin Notification' class TriggerEvent(models.TextChoices): ENROLLMENT = 'ENROLLMENT', 'Enrollment' ANNOUNCEMENT = 'ANNOUNCEMENT', 'Announcement' PROMOTIONAL = 'PROMOTIONAL', 'Promotional' RESET_PASSWORD = 'RESET_PASSWORD', 'Reset Password' class NotificationTemplate(models.Model): title = models.CharField(max_length=255) template = models.TextField(help_text='Use placeholders like {{username}} for personalization.') channel = models.CharField(max_length=20, choices=ChannelType.choices, default=ChannelType.APP) triggered_by = models.CharField(max_length=20, choices=TriggeredByType.choices, default=TriggeredByType.SYSTEM) trigger_event = models.CharField(max_length=50, choices=TriggerEvent.choices, help_text='Event that triggers this template.') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
该服务将所有内容联系在一起,根据通知渠道选择适当的策略。
class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="notifications") content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name="notifications") payload = models.JSONField(default=dict, help_text="Data to replace template placeholders.") is_read = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True)
以下是如何使用通知服务:
class StatusType(models.TextChoices): PENDING = 'PENDING', 'Pending' SUCCESS = 'SUCCESS', 'Success' FAILED = 'FAILED', 'Failed' class EmailNotification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='email_notifications') content = models.ForeignKey(NotificationTemplate, on_delete=models.CASCADE, related_name='email_notifications') payload = models.JSONField(default=dict) status = models.CharField(max_length=20, choices=StatusType.choices, default=StatusType.PENDING) status_reason = models.TextField(null=True) @property def email_content(self): """ Populate the template with dynamic data from the payload. """ content = self.content.template for key, value in self.payload.items(): content = re.sub( rf"{{{{\s*{key}\s*}}}}", str(value), content, ) return content
如果您发现本指南很有帮助且富有洞察力,请不要忘记点赞并关注以获取更多此类内容。您的支持激励我分享更多实用的实现和深入的教程。让我们继续一起构建令人惊叹的应用程序!
以上是在 Django 中构建灵活的通知系统:综合指南的详细内容。更多信息请关注PHP中文网其他相关文章!