轮询
通过定时器每隔多少秒发送一次请求。
<!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>
app.py
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) #多线程
app1.py
from flask import Flask,render_template,request,jsonify app = Flask(__name__) import queue q = queue.Queue() @app.route('/get/vote') def get_vote(): try: val = q.get(timeout=20) except queue.Empty: val = "已超时" return val @app.route('/vote') def vote(): q.put('10') return '投票成功' if __name__ == '__main__': # app.run(host='192.168.13.253',threaded=True) app.run(threaded=True)
队列.py
import queue q = queue.Queue() q.put('123') val = q.get() print(val) try: val = q.get(timeout=5) print(val) except queue.Empty: pass
长轮询
用法:让浏览器发送一次请求,会把请求夯住,最多会夯住多少秒,如果在这一段时间内,没有人再来发送数据,就让他等30秒释放,如果在这30秒中有人发数据,会立即拿到结果立即返回。
优势:结果实时化,省去了连接的次数
应用场景:
-实时
-在线
websocket也可以实现以上场景,但兼容性不好(基于html5)
长轮询兼容性好
<!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>
app.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=5) 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)
app1.py
from flask import Flask,render_template,request,jsonify app = Flask(__name__) import queue q = queue.Queue() @app.route('/get/vote') def get_vote(): try: val = q.get(timeout=20) except queue.Empty: val = "已超时" return val @app.route('/vote') def vote(): q.put('10') return '投票成功' if __name__ == '__main__': # app.run(host='192.168.13.253',threaded=True) app.run(threaded=True)
队列.py
import queue q = queue.Queue() q.put('123') val = q.get() print(val) try: val = q.get(timeout=5) print(val) except queue.Empty: pass