zoukankan      html  css  js  c++  java
  • python 轮询,长轮询

    轮询相关

    用于消息和投票等

    轮询

    1.采用js 定时请求。

    html

    <!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>
    View Code

    python

    from flask import Flask,render_template,request,jsonify
    
    
    app = Flask(__name__)
    
    
    USERS = {
        '1':{'name':'jack','count':1},
        '2':{'name':'rose','count':0},
        '3':{'name':'anner','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)
    View Code

    长轮询

    1.采用队列,递归,多线程实现。

    html

    <!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>
    View Code

    python

    from flask import Flask,render_template,request,jsonify,session
    import uuid
    import queue
    
    app = Flask(__name__)
    app.secret_key = 'asdfasdfasd'
    
    
    USERS = {
        '1':{'name':'jack','count':1},
        '2':{'name':'rose','count':0},
        '3':{'name':'anner','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=5)
            ret['data'] = users
        except queue.Empty:
            ret['status'] = False
    
        return jsonify(ret)
    
    
    
    if __name__ == '__main__':
        app.run(host='192.168.3.10',threaded=True)
        # app.run(threaded=True)
    View Code
  • 相关阅读:
    2018 BAT最新 php面试必考题
    2018 BAT最新《前端必考面试题》
    BAT-Java必考面试题集
    BAT-Python面试题
    BAT大数据面试题
    特殊密码锁 的通过码是:(请注意,在openjudge上提交了程序并且通过以后,就可以下载到通过码。请注意看公告里关于编程作业的说明)
    OpenJudge百炼-2747-数字方格-C语言-枚举
    poj2814-拨钟问题-C语言-枚举算法
    中国MOOC_面向对象程序设计——Java语言_第4章 继承与多态_第4周编程题
    中国MOOC_面向对象程序设计——Java语言_第3周 对象容器_1查找里程
  • 原文地址:https://www.cnblogs.com/huay/p/11624157.html
Copyright © 2011-2022 走看看