Flask长轮询即时消息
轮询和长轮询
轮询是每隔多久的时间请求一次
长轮询是请求到来就夯住,并设置超时时间,有值就瞬间返回。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask, render_template, session, request, jsonify import queue import uuid app = Flask(__name__) app.secret_key = str(uuid.uuid4()) USERS = { '1': {'name': '小黑', 'count': 1}, '2': {'name': '小胖', 'count': 0}, '3': {'name': '小铁锤', 'count': 0}, } QUEUE_DICT = { # 'uuid': Queue()队列 格式 } @app.route("/user/list") def user_list(): user_uuid = str(uuid.uuid4()) # 生成用户随机字符串 QUEUE_DICT[user_uuid] = queue.Queue() # 引用队列消息 session["current_user_uuid"] = user_uuid # session存放uuid字符串 return render_template("user_list.html", users=USERS) @app.route("/vote", methods=["POST"]) def vote(): uid = request.form.get('uid') # 获取uuid值 USERS[uid]['count'] += 1 # 让字典中的值自增 for q in QUEUE_DICT.values(): # 循环获取队列中的值并添加到USERS q.put(USERS) return "投票成功" @app.route("/get/vote", methods=["get"]) def get_vote(): user_uuid = session["current_user_uuid"] # 获取session中的存储的uuid值 q = QUEUE_DICT[user_uuid] # 获取字典中uuid对应的Q() ret = {"status": True, "data": None} # 返回状态码 try: users = q.get(timeout=5) # 异常就夯(hang)住5秒 ret["data"] = users except queue.Empty: ret["status"] = False return jsonify(ret)
html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width initial-scale=1.0"> <title>Title</title> <style> li{cursor: pointer; background-color: dodgerblue; margin: 10px; padding: 10px; list-style-type: none; text-align: center; font-size: 18px; } </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"); // 找到id $.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", // 获取json的数据格式 success:function (arg) { if(arg.status){ $("#userList").empty(); // 清空页面 $.each(arg.data, function (k, v) { // 循环 var li = document.createElement("li"); // 生成li标签 li.setAttribute("uid", k); // 设置属性uid=k li.innerText = v.name + "(" + v.count + ")"; // 拼接内容 $("#userList").append(li); }) } get_vote(); // 和前面的调用形成循环 } }) } </script> </body> </html>