一个纯粹基于jQuery和Django的SSE站内信通知的例子

这两天写了一个基于SSE技术的站内信通知红点的例子。现在来总结一下。

首先,站内信红点的实现方式基本上就三种:网页上设置一个Timer然后定时轮询;开一个WebSocket长链接;基于SSE的流模式。最终想试试SSE,就写了这个例子。

其次,SSE的实现也有很多种:第一种基于SSE.js;第二种是PHP;第三种是django。我采用的是django。网上大部分的例子都是需要第三方库: django-sse或者Daphen。我就是想基于原生jQuery和Django来实现。最后找了一个好方法,特此记录一下。

Django端的views代码:

复制代码
def get_unread_message_count_view(request):
    def event_stream():
        while True:
            # 从数据库或其他数据源获取数据
            messages = Messages.objects.filter(read_flag=False)
            unread_message_count = messages.count()
            # 构造SSE消息
            event = 'message'
            message = f'data: {unread_message_count}\n\n'
            yield f'event: {event}\n{message}'

    response = StreamingHttpResponse(event_stream(), content_type='text/event-stream')
    response['Cache-Control'] = 'no-cache'
    return response

urls就是标准的代码

网页端:

复制代码
<div class="fa-stack fa-2x" id="message_bell" data-count="10">
    <i class="fa fa-circle fa-stack-2x"></i>
    <i class="fa fa-bell fa-stack-1x fa-inverse"></i>
</div>
复制代码
<script type="text/javascript">
        $(function () {
            $(document).ready(function() {
            //data根据需求自定义参数
            const eventSource = new EventSource('get_unread_message_count');

            eventSource.addEventListener('message', function(event) {
                const data = event.data;
                $("#message_bell").attr("data-count",data);
                if (data == 0) {
                    $('.fa-stack').addClass('hidden');
                }
                else {
                    $('.fa-stack').removeClass('hidden');
                }
                // 处理收到的数据
            });

            });
        });
    </script>
相关推荐
趙卋傑14 分钟前
项目发布部署
linux·服务器·后端·web
没有梦想的咸鱼185-1037-166326 分钟前
【遥感技术】从CNN到Transformer:基于PyTorch的遥感影像、无人机影像的地物分类、目标检测、语义分割和点云分类
pytorch·python·深度学习·机器学习·数据分析·cnn·transformer
钟爱蛋炒饭31 分钟前
基于深度学习神经网络协同过滤模型(NCF)的视频推荐系统
python·神经网络·机器学习
eqwaak031 分钟前
Python Pillow库详解:图像处理的瑞士军刀
开发语言·图像处理·python·语言模型·pillow
RE-190142 分钟前
制冷剂中表压对应温度值的获取(Selenium)
爬虫·python·selenium·jupyter·pandas·danfoss·reftools
测试老哥1 小时前
Python+selenium自动化生成测试报告
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
数据知道1 小时前
Go基础:Go语言能用到的常用时间处理
开发语言·后端·golang·go语言
IT北辰2 小时前
Linux 系统python环境( Miniconda),最新版
linux·运维·python
不爱编程的小九九2 小时前
小九源码-springboot048-基于spring boot心理健康服务系统
java·spring boot·后端
龙茶清欢2 小时前
Spring Boot 应用启动组件加载顺序与优先级详解
java·spring boot·后端·微服务