首页 > 解决方案 > Flask SocketIO 通知

问题描述

我目前正在尝试弄清楚如何使 socketIO 适用于推送通知。我不知道如何将数据库信息发送到套接字以及如何在 Jquery 中翻译...

我想要做的是比较用户上次看到通知下拉列表的时间,如果用户的时间戳比数据库通知更早,我想用未看到的通知数量创建一个跨度。

这是我的 route.py :

@socketio.on('notif')
def handle_message():
    if current_user.is_authenticated:
        notif = Notification.query.filter(
        Notification.timestamp < current_user.last_seen_notification)
        n = len(notif)
    send(n)

@app.route('/notification', methods=["POST"])
def notification():
    current_user.last_seen_notification = datetime.datetime.now()
    db.session.commit()
    return 'Ok'

我有我的 html :

    <li class="dropdown nav-item">
<a href="#" class="dropdown-toggle nav-link" data-toggle="dropdown" id="notifbtn">
<i class="nc-icon nc-planet"></i>
<span class="notification"></span>
<span class="d-lg-none">Notification</span>
</a>
<ul class="dropdown-menu">
<a class="dropdown-item" href="#">Notification 1</a>
<a class="dropdown-item" href="#">Notification 2</a>
<a class="dropdown-item" href="#">Notification 3</a>
<a class="dropdown-item" href="#">Notification 4</a>
<a class="dropdown-item" href="#">Another notification</a>
</ul>
</li>

和我的 javascript :

$(document).ready(function() {

    $("#notifbtn").on('click', function() {
        $.ajax({
            type : 'POST',
            url : '/notification'
        })
    });

    var socket = io.connect('http://127.0.0.1:5000');

    socket.on('notif', function() {
        $('.notification').text(n);
        console.log('Received message');
    });
});

我的带有下拉菜单的 javascript 效果很好,当用户单击下拉菜单时,他的 last_seen_notification 变量会更新。

但我不知道如何使 socketio 工作。

谢谢

标签: pythonflasksocket.ioflask-socketio

解决方案


推荐阅读