方案一:用户手动刷新

方案二:用轮询实现票数实时显示--flask

在前端页面写一个函数,每个两秒刷新页面

from flask import Flask,request,render_template,redirect,session

app = Flask(__name__)
app.secret_key = 'asdfasdf'
@app.before_request
def check_login():
    if request.path == '/login':
        return None
    user = session.get('user_info')
    if not user:
        return redirect('/login')

@app.route('/login',methods=['GET',"POST"])
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        session['user_info'] = user
        return redirect('/index')


GENTILEMAN = {
    '1':{'name':'向龙','count':0},
    '2':{'name':'霄汉','count':0},
}

@app.route('/index')
def index():
    return render_template('index.html',gg=GENTILEMAN)


if __name__ == '__main__':
    app.run()
app.py
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<form method="post">
    <input type="text" name="user">
    <input type="text" name="pwd">
    <input type="submit" value="提交">
</form>

</body>
</html>
login.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
    <h1>请选出最帅的男人</h1>
    <ul>
        {% for k,v in gg.items() %}
            <li>ID:{{ k }}, 姓名:{{ v.name }} ,票数:{{ v.count }}</li>
        {% endfor %}
    </ul>

    <script>
        setInterval(function () {
            location.reload();
        },2000)
    </script>
</body>
</html>
index.html

 方案二:用长轮询实现票数实时显示

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<form method="post">
    <input type="text" name="user">
    <input type="text" name="pwd">
    <input type="submit" value="提交">
</form>

</body>
</html>
login.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
    <h1>请选出最帅的男人</h1>
    <ul>
        {% for k,v in gg.items() %}
            <li style="cursor: pointer" id="user_{{ k }}" ondblclick="vote({{ k }});">ID:{{ k }}, 姓名:{{ v.name }} ,票数:<span>{{ v.count }}</span></li>
        {% endfor %}
    </ul>

    <script src="/static/jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
            get_new_count();
        });
        
        function get_new_count() {
            $.ajax({
                url: '/get_new_count',
                type:'GET',
                dataType:'JSON',
                success:function (arg) {
                    if (arg.status){
                        // 更新票数
                        var gid = "#user_" + arg.data.gid;
                        $(gid).find('span').text(arg.data.count);
                    }else{
                        // 10s内没有人投票
                    }
                    get_new_count();

                }
            })
        }

        function vote(gid) {
            $.ajax({
                url: '/vote',
                type:'POST',
                data:{gid:gid},
                dataType:"JSON",
                success:function (arg) {

                }
            })
        }
    </script>
</body>
</html>
index.html
from flask import Flask,request,render_template,redirect,session,jsonify
import uuid
import queue

app = Flask(__name__)
app.secret_key = 'asdfasdf'

USER_QUEUE = {

}

@app.before_request
def check_login():
    if request.path == '/login':
        return None
    user = session.get('user_info')
    if not user:
        return redirect('/login')

@app.route('/login',methods=['GET',"POST"])
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        uid = str(uuid.uuid4())
        USER_QUEUE[uid] = queue.Queue()
        session['user_info'] = {'uid':uid,'name':user}
        return redirect('/index')


GENTILEMAN = {
    '1':{'name':'向龙','count':0},
    '2':{'name':'霄汉','count':0},
}

@app.route('/index')
def index():
    return render_template('index.html',gg=GENTILEMAN)

@app.route('/get_new_count')
def get_new_count():
    """
    获取用户session中的uid
    根据uid获取当前登录用的队列
    :return:
    """
    ret = {'status':True,'data':None }
    uid = session['user_info']['uid']
    q = USER_QUEUE[uid]
    try:
        data = q.get(timeout=10)
        ret['data'] = data
    except queue.Empty as e:
        ret['status'] = False

    return jsonify(ret)

@app.route('/vote',methods=['POST'])
def vote():
    """
    接收用户请求,对帅哥进行投票
    :return:
    """
    gid = request.form.get('gid')
    old = GENTILEMAN[gid]['count']
    new = old + 1
    GENTILEMAN[gid]['count'] = new

    data = {'gid':gid,'count':new}
    for q in USER_QUEUE.values():
        q.put(data)

    return 'OK'




if __name__ == '__main__':
    app.run(host='0.0.0.0',threaded=True)
app.py

使用redis的列表实现:

from flask import Flask,request,render_template,redirect,session,jsonify
import uuid
import queue
import json

app = Flask(__name__)
app.secret_key = 'asdfasdf'
import redis
conn = redis.Redis(host='127.0.0.1', port=6379)

GENTILEMAN = {
    '1':{'name':'向龙','count':0},
    '2':{'name':'霄汉','count':0},
}

@app.before_request
def check_login():
    if request.path == '/login':
        return None
    user = session.get('user_info')
    if not user:
        return redirect('/login')

@app.route('/login',methods=['GET',"POST"])
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        uid = str(uuid.uuid4())
        conn.lpush('xxxxxxxxxxxxxxxxx',uid)
        session['user_info'] = {'uid':uid,'name':user}
        return redirect('/index')

@app.route('/index')
def index():
    return render_template('index.html',gg=GENTILEMAN)

@app.route('/get_new_count')
def get_new_count():
    """
    获取用户session中的uid
    根据uid获取当前登录用的队列
    :return:
    """
    ret = {'status':True,'data':None }
    uid = session['user_info']['uid']

    data = conn.brpop(uid,timeout=20)
    if not data:
        ret['status'] = False
    else:
        # print(data[1]) # {'gid':gid,'count':new}
        data_str = str(data[1], encoding='utf-8')
        data_dict = json.loads(data_str)
        ret['data'] = data_dict
    return jsonify(ret)

@app.route('/vote',methods=['POST'])
def vote():
    """
    接收用户请求,对帅哥进行投票
    :return:
    """
    gid = request.form.get('gid')
    old = GENTILEMAN[gid]['count']
    new = old + 1
    GENTILEMAN[gid]['count'] = new

    data = json.dumps({'gid':gid,'count':new})
    uid_list = conn.lrange('xxxxxxxxxxxxxxxxx', 0, conn.llen('xxxxxxxxxxxxxxxxx'))
    for uid in uid_list:
        conn.lpush(uid, data)
    return 'OK'


if __name__ == '__main__':
    app.run(host='0.0.0.0',threaded=True)
app.py
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<form method="post">
    <input type="text" name="user">
    <input type="text" name="pwd">
    <input type="submit" value="提交">
</form>

</body>
</html>
login.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
    <h1>请选出最帅的男人</h1>
    <ul>
        {% for k,v in gg.items() %}
            <li style="cursor: pointer" id="user_{{ k }}" ondblclick="vote({{ k }});">ID:{{ k }}, 姓名:{{ v.name }} ,票数:<span>{{ v.count }}</span></li>
        {% endfor %}
    </ul>

    <script src="/static/jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
            get_new_count();
        });
        
        function get_new_count() {
            $.ajax({
                url: '/get_new_count',
                type:'GET',
                dataType:'JSON',
                success:function (arg) {
                    if (arg.status){
                        // 更新票数
                        var gid = "#user_" + arg.data.gid;
                        $(gid).find('span').text(arg.data.count);
                    }else{
                        // 10s内没有人投票
                    }
                    get_new_count();

                }
            })
        }

        function vote(gid) {
            $.ajax({
                url: '/vote',
                type:'POST',
                data:{gid:gid},
                dataType:"JSON",
                success:function (arg) {

                }
            })
        }
    </script>
</body>
</html>
index.html

 

posted on 2018-05-17 19:22  Py行僧  阅读(994)  评论(0编辑  收藏  举报