我需要使用python中的socket IO和flask框架显示实时用户状态(绿灯)和脱机状态

2024-04-20 01:46:39 发布

您现在位置:Python中文网/ 问答频道 /正文

当用户关闭浏览器后无法更新状态以使用户处于活动状态时,我遇到问题。我需要向用户显示实时或离线状态,如whatsapp如果用户在线,则显示在线用户;如果用户长时间不活动,则显示离线状态,然后他/她关闭浏览器,则显示用户离线。 我正在使用Flask框架、Mysql数据库和Socket IO。请帮我解决这个问题。我正在分享我的代码,实际上我做了什么

<script type="text/javascript" charset="utf-8">
   
    $("#__lgFr").on('submit',function(e){
        e.preventDefault();
        var fromData = $(this).serialize();
        // call for login validation and after successful login updated the login_status as True in login route
        $.ajax({
            url:'{{url_for('login')}}',
            method:'POST',
            data:fromData,
             
            success:function(response){
                if(response.error==0){
                    socket.emit('online',{'user_id':response.user_id,'username':response.name,'id':response.id});
                    setTimeout(function(){
                        window.location.href=response.url;
                    },2000)
                }    
            } 
        });
    });
     //Fetch all the Users from the databases to show all with status code
        socket.on('status_change', function(data) {
            var url = "/api/list/subscriber";
            $.get( url,function(response){
                $("#__sublt").html(response);
            });
        });

        $("#__lgo").on('click',function(){
            $.get('/logout',function(response){
                setTimeout(function(){
                    window.location.href='/login';
                },2000);
                socket.emit('offline');    
            });
        });


</script>

//Python server code for socket IO

@socketio.on('online')
def online(data):
    emit('status_change', {'member_id': data['id'],'username': data['user_id']+' is online.', 'status': 'online'}, broadcast=True)


@socketio.on('offline')
def offline():
    emit('status_change', {'status': 'offline'}, broadcast=True)

//Table
[1]: https://i.stack.imgur.com/W5aDB.png

Tags: 用户idurldataonresponse状态status