• 基于轮询实现实时的在线投票系统


    需求

      用户在投票的页面可以实时的监测到,投票详情

    在这里我会通过轮询和长轮询(推荐使用这个,可以减少请求数,实时性也好)的方法来实现

    基于轮询实现投票系统

    大致的思路是前端开启一个定时器每隔10秒定时的向服务器获取投票的结果

    from flask import Flask,render_template,request,jsonify
    
    
    app = Flask(__name__)
    
    
    USERS = {
        '1':{'name':'贝贝','count':1},
        '2':{'name':'小东北','count':0},
        '3':{'name':'何伟明','count':0},
    }
    
    @app.route('/user/list')
    def user_list():
        import time
        return render_template('user_list.html',users=USERS)
    
    @app.route('/vote',methods=['POST'])
    def vote():
        uid = request.form.get('uid')
        USERS[uid]['count'] += 1
        return "投票成功"
    
    @app.route('/get/vote',methods=['GET'])
    def get_vote():
    
        return jsonify(USERS)
    
    
    if __name__ == '__main__':
        # app.run(host='192.168.13.253',threaded=True)
        app.run(threaded=True)
    
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            li{
                cursor: pointer;
            }
        </style>
    </head>
    <body>
        <ul id="userList">
            {% for key,val in users.items() %}
                <li uid="{{key}}">{{val.name}} ({{val.count}})</li>
            {% endfor %}
        </ul>
    
        <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
        <script>
    
            $(function () {
                $('#userList').on('dblclick','li',function () {
                    var uid = $(this).attr('uid');
                    $.ajax({
                        url:'/vote',
                        type:'POST',
                        data:{uid:uid},
                        success:function (arg) {
                            console.log(arg);
                        }
                    })
                });
    
            });
    
    
            /*
            获取投票信息
             */
            function get_vote() {
                $.ajax({
                    url:'/get/vote',
                    type:"GET",
                    dataType:'JSON',
                    success:function (arg) {
                        $('#userList').empty();
                        $.each(arg,function (k,v) {
                            var li = document.createElement('li');
                            li.setAttribute('uid',k);
                            li.innerText = v.name + "(" + v.count + ')' ;
                            $('#userList').append(li);
                        })
    
                    }
                })
            }
    
    
            setInterval(get_vote,3000);
    
        </script>
    </body>
    </html>
    templates/user_list.html

    缺点 : 获取票数的实时性不好,频繁的向服务器发送请求  

    基于长轮询实现投票系统

    基本的思路:

       前端: 通过递归发送查询投票详情的请求,更新数据  (数据驱动模型)

       服务端 :如果没有人来投票服务器把所有用户的请求hang住10秒,把原有的信息返回,如果在这等待的10s中有人来投票,直接返回最新的结果给所有hang住的用户

    基于队列queue的阻塞, 来实现hang住请求,queue的基本用法如下

    import queue
    
    q = queue.Queue()
    
    
    val = q.get()
    print(val)
    
    try:
        val = q.get(timeout=10)
        print(val)
    except queue.Empty:
        pass
    

    run.py

    from flask import Flask,render_template,request,jsonify,session
    import uuid
    import queue
    
    app = Flask(__name__)
    app.secret_key = 'asdfasdfasd'
    
    
    USERS = {
        '1':{'name':'贝贝','count':1},
        '2':{'name':'小东北','count':0},
        '3':{'name':'何伟明','count':0},
    }
    
    QUEQUE_DICT = {
        # 'asdfasdfasdfasdf':Queue()
    }
    
    @app.route('/user/list') 
    def user_list():
        user_uuid = str(uuid.uuid4())
        QUEQUE_DICT[user_uuid] = queue.Queue()
    
        session['current_user_uuid'] = user_uuid
        return render_template('user_list.html',users=USERS)
    
    @app.route('/vote',methods=['POST'])
    def vote():
        uid = request.form.get('uid')
        USERS[uid]['count'] += 1
        for q in QUEQUE_DICT.values():
            q.put(USERS)
        return "投票成功"
    
    
    @app.route('/get/vote',methods=['GET'])
    def get_vote():
        user_uuid = session['current_user_uuid']
        q = QUEQUE_DICT[user_uuid]
    
        ret = {'status':True,'data':None}
        try:
            users = q.get(timeout=10)
            ret['data'] = users
        except queue.Empty:
            ret['status'] = False
    
        return jsonify(ret)
    
    
    
    if __name__ == '__main__':
        app.run(host='192.168.13.253',threaded=True)
        # app.run(threaded=True)
    

      

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            li{
                cursor: pointer;
            }
        </style>
    </head>
    <body>
        <ul id="userList">
            {% for key,val in users.items() %}
                <li uid="{{key}}">{{val.name}} ({{val.count}})</li>
            {% endfor %}
        </ul>
    
        <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
        <script>
    
            $(function () {
                $('#userList').on('click','li',function () {
                    var uid = $(this).attr('uid');
                    $.ajax({
                        url:'/vote',
                        type:'POST',
                        data:{uid:uid},
                        success:function (arg) {
                            console.log(arg);
                        }
                    })
                });
                get_vote();
            });
    
            /*
            获取投票信息
             */
            function get_vote() {
                $.ajax({
                    url:'/get/vote',
                    type:"GET",
                    dataType:'JSON',
                    success:function (arg) {
                        if(arg.status){
                            $('#userList').empty();
                                $.each(arg.data,function (k,v) {
                                    var li = document.createElement('li');
                                    li.setAttribute('uid',k);
                                    li.innerText = v.name + "(" + v.count + ')' ;
                                    $('#userList').append(li);
                                })
                        }
                        get_vote();
    
                    }
                })
            }
    
        </script>
    </body>
    </html>
    templates/user_list.html
  • 相关阅读:
    CreateProcess逆向分析3环用户层逆向分析(一)
    CVE20112005(MS11080)漏洞分析
    vmware安装Windows 11虚拟机
    SAP SD 常用配置事物代码
    Java学习笔记02面向对象
    Java学习笔记01基本语法
    Java学习笔记03枚举和注解
    openssl3.0 加密算法库编程精要 06 详解 EVP API 公开密钥密码算法 非对称加密、签名
    零基础实现微信小程序云开发的无人机管理系统项目实例系列教程简述(一)
    chrome安装vuedevtools遇到的常见问题及解决方法
  • 原文地址:https://www.cnblogs.com/crazymagic/p/9746299.html
Copyright © 2020-2023  润新知