长轮询

长轮询,投票系统,没人投票hold住,有投票,实时刷新

app.py
from flask import Flask, render_template, request, jsonify, session
import uuid
import queue

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


USERS = {
    '1': {'name': 'a', 'count': 1},
    '2': {'name': 'b', 'count': 0},
    '3': {'name': 'c', 'count': 0},
}

QUEUE_DICT = {
    #  'uuid':Queue()
}


@app.route('/user/list')
def user_list():
    user_uuid = str(uuid.uuid4())
    QUEUE_DICT[user_uuid] = queue.Queue()       # 对不同的访问用户根据uuid创建不同的队
    session['current_user_uuid'] = user_uuid    # 存到session中
    return render_template('user_list.html', users=USERS)


@app.route('/vote', methods=['POST'])
def vote():
    uid = request.form.get('uid')  # 前端发来的ajax的post请求
    USERS[uid]['count'] += 1
    for q in QUEUE_DICT.values():  # 为队列每个用户加入最新投票结果
        q.put(USERS)
    return "投票成功"


@app.route('/get/vote', methods=['GET'])
def get_vote():
    user_uuid = session['current_user_uuid']
    q = QUEUE_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(threaded=True)
user_list.html



    
    Title
    
    


    
    {% for key,val in users.items() %}
  • {{val.name}} ({{val.count}})
  • {% endfor %}

 

你可能感兴趣的:(长轮询)