轮询:通过定时器,每x秒钟发送请求
长轮询:浏览器发送请求,最多夯住y秒,一旦发生变化立即返回结果。
应用:实时, 在线
websocket实现(兼容性不好)
基于轮询实现投票系统
源代码:
<!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"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <meta name="description" content=""> <meta name="author" content=""> <title>投票系统</title> <!-- Bootstrap core CSS --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="static/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <link href="static/plugins/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="static/css/dashboard.css" rel="stylesheet"> <script src="static/js/ie-emulation-modes-warning.js"></script> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">投票系统</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a class="item" href="#">消息<i style="margin-left: 3px;" class="fa fa-bell-o" aria-hidden="true"></i> <span class="badge" style="background-color: red">4</span></a> </li> <li><a class="item" href="#">通知<i style="margin-left: 3px;" class="fa fa-envelope-o" aria-hidden="true"></i> <span class="badge" style="background-color:forestgreen">4</span></a> </li> <li><a class="item" href="#">任务<i style="margin-left: 3px;" class="fa fa-commenting-o" aria-hidden="true"></i> <span class="badge" style="background-color: forestgreen">4</span></a> </li> <li><a href="https://v3.bootcss.com/examples/dashboard/#"></a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">张亚飞 <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">个人信息</a></li> <li><a href="#">退出</a></li> </ul> </li> </ul> <form class="navbar-form navbar-right"> <input type="text" class="form-control" placeholder="Search..."> </form> </div> </div> </nav> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar"> <li class="active"><a href="#">投票系统<span class="sr-only">(current)</span></a></li> </ul> </div> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h1 class="page-header">候选人</h1> <ul id="userList" class="row placeholders"> {% for key,val in users.items() %} <div class="col-xs-6 col-sm-3 placeholder"> <img src="{{ val['image'] }}" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail"> <h4> {{ val['name'] }} <span class="badge" style="background-color: red">{{ val['count'] }}</span> </a> </h4> <li uid="{{key}}" class="text-muted btn btn-primary">投票</li> </div> {% endfor %} </ul> </div> </div> </div> </div> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>')</script> <script src="https://cdn.bootcss.com/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script> <!-- Just to make our placeholder images work. Don't actually copy the next line! --> <script src="static/js/holder.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="static/js/ie10-viewport-bug-workaround.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) { // window.location.reload(); window.history.go(0); } get_vote(); } }) } </script> </body> </html>
# -*- coding: utf-8 -*- """ @Datetime: 2019/1/4 @Author: Zhang Yafei """ from flask import Flask,render_template,request,jsonify,session import uuid import queue app = Flask(__name__) app.secret_key = 'asdfasdfasd' # app.config['DEBUG'] = True USERS = { '1':{'name':'姚明','count':1,'image':'static/images/姚明.jpg'}, '2':{'name':'詹姆斯','count':0,'image':'static/images/詹姆斯.jpg'}, '3':{'name':'科比','count':0,'image':'static/images/科比.jpg'}, } QUEQUE_DICT = { # 'asdfasdfasdfasdf':Queue() } @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) @app.route('/home') def home(): user_uuid = str(uuid.uuid4()) QUEQUE_DICT[user_uuid] = queue.Queue() session['current_user_uuid'] = user_uuid return render_template('home.html', users=USERS) if __name__ == '__main__': # app.run(host='192.168.13.253',threaded=True) app.run(threaded=True)