Pemberitahuan ialah komponen utama mana-mana aplikasi web moden, memastikan pengguna dimaklumkan dan terlibat. Sistem pemberitahuan yang dilaksanakan dengan baik boleh mengendalikan berbilang saluran seperti makluman dalam apl, e-mel dan SMS sambil menyesuaikan kandungan secara dinamik untuk pengalaman pengguna yang lancar. Dalam panduan ini, kami akan membimbing anda membuat sistem pemberitahuan yang teguh dan berskala dalam Django.
Sistem pemberitahuan kami direka untuk menyediakan:
Templat bertindak sebagai tulang belakang sistem kami, menyimpan kandungan boleh guna semula untuk pemberitahuan.
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)
Ciri Utama:
Model Pemberitahuan memautkan templat kepada pengguna dan menyimpan sebarang muatan dinamik untuk pemperibadian.
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)
Untuk mengendalikan e-mel dan SMS secara unik, kami mentakrifkan model tertentu.
Pemberitahuan E-mel
Model ini mengurus data khusus e-mel, seperti penjanaan mesej dinamik dan penjejakan penghantaran.
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
Pemberitahuan SMS
Sama seperti pemberitahuan e-mel, logik khusus SMS dilaksanakan di sini.
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
Untuk memudahkan pengurusan pemberitahuan, kami mendaftarkan model dalam panel pentadbir 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']
Kami akan melaksanakan lapisan perkhidmatan untuk mengurus penghantaran pemberitahuan melalui pelbagai saluran.
Menggunakan Corak Strategi, kami akan menentukan kelas untuk setiap saluran pemberitahuan.
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)
Perkhidmatan ini menggabungkan segala-galanya, memilih strategi yang sesuai berdasarkan saluran pemberitahuan.
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)
Berikut ialah cara anda boleh menggunakan perkhidmatan pemberitahuan:
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
Jika anda mendapati panduan ini membantu dan bernas, jangan lupa untuk menyukai dan mengikuti untuk lebih banyak kandungan seperti ini. Sokongan anda mendorong saya untuk berkongsi lebih banyak pelaksanaan praktikal dan tutorial yang mendalam. Mari kita terus membina aplikasi yang menakjubkan bersama-sama!
Atas ialah kandungan terperinci Membina Sistem Pemberitahuan Fleksibel dalam Django: Panduan Komprehensif. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!