一文教你实战构建消息通知系统Django

打印 上一主题 下一主题

主题 570|帖子 570|积分 1712

本文分享自华为云社区《构建实时消息通知系统:Django实战指南》,作者:柠檬味拥抱。
在Web应用步伐中,实现消息通知系统是至关重要的,它可以资助用户实时了解到与其相关的事件或动态。Django提供了信号机制,可以用于实现这样的通知系统。本文将介绍如何使用Django的信号机制来构建一个简单但功能强大的消息通知系统,并提供相应的代码和实例。
1. 安装 Django

起首,确保你已经安装了 Django。你可以通过 pip 安装它:
  1. pip install django
复制代码
2. 创建 Django 项目和应用

创建一个 Django 项目,并在其中创建一个应用:
  1. django-admin startproject notification_system
  2. cd notification_system
  3. python manage.py startapp notifications
复制代码
3. 定义模型

在 notifications/models.py 文件中定义一个模型来存储通知信息:
  1. from django.db import models
  2. from django.contrib.auth.models import User
  3. class Notification(models.Model):
  4.     user = models.ForeignKey(User, on_delete=models.CASCADE)
  5.     message = models.CharField(max_length=255)
  6.     created_at = models.DateTimeField(auto_now_add=True)
  7.     read = models.BooleanField(default=False)
复制代码
4. 创建信号

在 notifications/signals.py 文件中创建信号,该信号将在需要发送通知时触发:
  1. from django.dispatch import Signal
  2. notification_sent = Signal(providing_args=["user", "message"])
复制代码
5. 编写信号处理器

在 notifications/handlers.py 文件中编写信号处理器,处理信号并创建相应的通知:
  1. from django.dispatch import receiver
  2. from .signals import notification_sent
  3. from .models import Notification
  4. @receiver(notification_sent)
  5. def create_notification(sender, **kwargs):
  6.     user = kwargs['user']
  7.     message = kwargs['message']
  8.     Notification.objects.create(user=user, message=message)
复制代码
6. 发送通知

在你的应用步伐中的适当位置,发送信号以触发通知:
  1. from django.contrib.auth.models import User
  2. from notifications.signals import notification_sent
  3. # 例如,发送通知给特定用户
  4. user = User.objects.get(username='username')
  5. notification_sent.send(sender=None, user=user, message='你有一个新消息')
复制代码
7. 表现通知

在你的应用步伐中,可以通过查询通知模型来表现用户的通知:
  1. from notifications.models import Notification
  2. # 例如,在视图中查询并显示通知
  3. def notifications_view(request):
  4.     user_notifications = Notification.objects.filter(user=request.user)
  5.     return render(request, 'notifications.html', {'notifications': user_notifications})
复制代码
8. 标志通知为已读

当用户查看通知时,你可能需要将它们标志为已读。你可以在视图中实验此操纵:
  1. def mark_as_read(request, notification_id):
  2.     notification = Notification.objects.get(pk=notification_id)
  3.     notification.read = True
  4.     notification.save()
  5.     return redirect('notifications_view')
复制代码
9. 定义通知模板

创建一个 HTML 模板来出现通知信息。在 templates/notifications.html 文件中定义:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Notifications</title>
  7. </head>
  8. <body>
  9.     <h1>Notifications</h1>
  10.     <ul>
  11.         {% for notification in notifications %}
  12.         <li{% if notification.read %} style="color: grey;"{% endif %}>
  13.             {{ notification.message }}
  14.             {% if not notification.read %}
  15.             <a target="_blank" href="https://www.cnblogs.com/{% url 'mark_as_read' notification.id %}">Mark as Read</a>
  16.             {% endif %}
  17.         </li>
  18.         {% endfor %}
  19.     </ul>
  20. </body>
  21. </html>
复制代码
10. 配置 URL

配置 URL 来处理通知相关的哀求。在 notification_system/urls.py 文件中:
  1. from django.urls import path
  2. from notifications.views import notifications_view, mark_as_read
  3. urlpatterns = [
  4.     path('notifications/', notifications_view, name='notifications_view'),
  5.     path('notifications/mark_as_read/<int:notification_id>/', mark_as_read, name='mark_as_read'),
  6. ]
复制代码
11. 运行服务器

运行 Django 服务器以查看结果:
  1. python manage.py runserver
复制代码
现在,你可以访问 http://127.0.0.1:8000/notifications/ 查看通知页面,并且点击“标志为已读”链接来标志通知。
12. 集成前端框架

为了提升通知页面的用户体验,我们可以使用一些盛行的前端框架来美化页面并添加一些交互功能。这里以Bootstrap为例。
起首,安装Bootstrap:
  1. pip install django-bootstrap4
复制代码
在 settings.py 中配置:
  1. INSTALLED_APPS = [
  2.     ...
  3.     'bootstrap4',
  4.     ...
  5. ]
复制代码
修改通知模板 notifications.html,引入Bootstrap的样式和JavaScript文件,并使用Bootstrap的组件来美化页面:
  1. {% load bootstrap4 %}
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5.     <meta charset="UTF-8">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title>Notifications</title>
  8.     {% bootstrap_css %}
  9. </head>
  10. <body>
  11.    
  12.         <h1 class="mt-5">Notifications</h1>
  13.         <ul class="list-group mt-3">
  14.             {% for notification in notifications %}
  15.             <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
  16.                 {{ notification.message }}
  17.                 {% if not notification.read %}
  18.                 <a target="_blank" href="https://www.cnblogs.com/{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary ml-2">Mark as Read</a>
  19.                 {% endif %}
  20.             </li>
  21.             {% endfor %}
  22.         </ul>
  23.    
  24.     {% bootstrap_javascript %}
  25. </body>
  26. </html>
复制代码
13. 使用 Ajax 实现标志为已读功能

我们可以使用 Ajax 技能来实现标志通知为已读的功能,这样可以避免刷新整个页面。修改模板文件和视图函数如下:
在模板中,使用 jQuery 来发送 Ajax 哀求:
  1. [/code]修改视图函数 mark_as_read:
  2. [code]from django.http import JsonResponse
  3. def mark_as_read(request, notification_id):
  4.     notification = Notification.objects.get(pk=notification_id)
  5.     notification.read = True
  6.     notification.save()
  7.     return JsonResponse({'success': True})
复制代码
14. 添加通知计数功能

为了让用户可以清晰地知道有多少未读通知,我们可以添加一个通知计数的功能,将未读通知的数量表现在页面上。
起首,在 notifications/views.py 中修改 notifications_view 视图函数:
  1. def notifications_view(request):
  2.     user_notifications = Notification.objects.filter(user=request.user)
  3.     unread_count = user_notifications.filter(read=False).count()
  4.     return render(request, 'notifications.html', {'notifications': user_notifications, 'unread_count': unread_count})
复制代码
然后,在通知模板中表现未读通知的数量:
  1.     <h1 class="mt-5">Notifications</h1>
  2.    
  3.         You have {{ unread_count }} unread notification(s).
  4.    
  5.     <ul class="list-group mt-3">
  6.         {% for notification in notifications %}
  7.         <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
  8.             {{ notification.message }}
  9.             {% if not notification.read %}
  10.             <a target="_blank" href="https://www.cnblogs.com/{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary ml-2 mark-as-read">Mark as Read</a>
  11.             {% endif %}
  12.         </li>
  13.         {% endfor %}
  14.     </ul>
复制代码
15. 实时更新通知计数

为了使通知计数实时更新,我们可以使用 Ajax 技能定期哀求服务器以获取最新的未读通知数量。
在通知模板中添加 JavaScript 代码:
  1. [/code]在 notifications/urls.py 中添加一个新的 URL 路由来处理未读通知数量的哀求:
  2. [code]from django.urls import path
  3. from .views import notifications_view, mark_as_read, unread_count
  4. urlpatterns = [
  5.     path('notifications/', notifications_view, name='notifications_view'),
  6.     path('notifications/mark_as_read/<int:notification_id>/', mark_as_read, name='mark_as_read'),
  7.     path('notifications/unread_count/', unread_count, name='unread_count'),
  8. ]
复制代码
末了,在 notifications/views.py 中定义 unread_count 视图函数:
  1. from django.http import JsonResponse
  2. def unread_count(request):
  3.     user_notifications = Notification.objects.filter(user=request.user, read=False)
  4.     unread_count = user_notifications.count()
  5.     return JsonResponse({'unread_count': unread_count})
复制代码
16. 添加通知删除功能

除了标志通知为已读之外,有时用户还可能希望能够删除一些通知,特别是一些不再需要的通知。因此,我们可以添加一个删除通知的功能。
起首,在模板中为每个通知添加一个删除按钮:
  1. <ul class="list-group mt-3">
  2.     {% for notification in notifications %}
  3.     <li class="list-group-item{% if notification.read %} list-group-item-light{% endif %}">
  4.         {{ notification.message }}
  5.         
  6.             {% if not notification.read %}
  7.             <a target="_blank" href="https://www.cnblogs.com/{% url 'mark_as_read' notification.id %}" class="btn btn-sm btn-primary mark-as-read">Mark as Read</a>
  8.             {% endif %}
  9.             <a target="_blank" href="https://www.cnblogs.com/{% url 'delete_notification' notification.id %}" class="btn btn-sm btn-danger delete-notification">Delete</a>
  10.         
  11.     </li>
  12.     {% endfor %}
  13. </ul>
复制代码
然后,在 notifications/urls.py 中添加一个新的 URL 路由来处理删除通知的哀求:
  1. urlpatterns = [
  2.     ...
  3.     path('notifications/delete/<int:notification_id>/', delete_notification, name='delete_notification'),
  4. ]
复制代码
接着,在 notifications/views.py 中定义 delete_notification 视图函数:
  1. def delete_notification(request, notification_id):
  2.     notification = Notification.objects.get(pk=notification_id)
  3.     notification.delete()
  4.     return redirect('notifications_view')
复制代码
末了,为了使用户可以通过 Ajax 删除通知,我们可以修改模板中的 JavaScript 代码:
  1. [/code][size=4]17. 添加异步使命处理[/size]
  2. 在实际应用中,通知系统可能需要处理大量的通知,而生成和发送通知可能是一个耗时的操纵。为了避免阻塞用户哀求,我们可以使用异步使命处理来处理通知的生成和发送。
  3. [size=3]17.1 安装 Celery[/size]
  4. 起首,安装 Celery 和 Redis 作为消息署理:
  5. [code]pip install celery redis
复制代码
17.2 配置 Celery

在 Django 项目的根目录下创建一个名为 celery.py 的文件,并添加以下内容:
  1. import os
  2. from celery import Celery
  3. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'notification_system.settings')
  4. app = Celery('notification_system')
  5. app.config_from_object('django.conf:settings', namespace='CELERY')
  6. app.autodiscover_tasks()
复制代码
在 settings.py 中添加 Celery 配置:
  1. CELERY_BROKER_URL = 'redis://localhost:6379/0'
复制代码
17.3 创建异步使命

在 notifications/tasks.py 中定义异步使命来处理通知的生成和发送:
  1. from celery import shared_task
  2. from .models import Notification
  3. @shared_task
  4. def send_notification(user_id, message):
  5.     user = User.objects.get(pk=user_id)
  6.     Notification.objects.create(user=user, message=message)
复制代码
17.4 触发异步使命

在你的应用步伐中,当需要发送通知时,使用 Celery 的 delay() 方法触发异步使命:
  1. from notifications.tasks import send_notification
  2. send_notification.delay(user_id, '你有一个新消息')
复制代码
总结:

本文介绍了如何使用 Django 构建一个功能强大的消息通知系统,其中涵盖了以下主要内容:

  • 通过定义模型、创建信号、编写信号处理器,实现了通知系统的基本框架。
  • 集成了前端框架 Bootstrap,并使用 Ajax 技能实现了标志通知为已读的功能,以及实时更新未读通知数量的功能,提升了用户体验。
  • 添加了通知删除功能,使用户可以更灵活地管理通知。
  • 引入了异步使命处理技能 Celery,将通知的生成和发送操纵转换为异步使命,提高了系统的性能和相应速度。
通过这些步调,我们建立了一个功能美满的消息通知系统,用户可以实时了解到与其相关的重要信息,并且可以自由地管理和处理通知,从而增强了应用的交互性、可用性和性能。
 
点击关注,第一时间了解华为云奇怪技能~
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

刘俊凯

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表