实时投票系统(基于flask和redis)
我们使用flask框架,只需要简单的4个文件夹即可完成
不需要用蓝图,就是简单的flask程序
静态文件static
模板templates
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1"> 7 <title>Title</title> 8 </head> 9 <body> 10 <form method="post"> 11 <input type="text"> 12 <input type="text"> 13 <input type="submit" value="提交"> 14 </form> 15 </body> 16 </html>
这里是核心代码块:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1"> 7 <title>Title</title> 8 </head> 9 <body> 10 <h3>choice the charming person</h3> 11 <ul> 12 {% for k,v in obj.items() %} 13 14 <!--这里的style设置的cursor:pointer让页面上这个li标签被鼠标触到的时候显示的是一个手掌的样式替代默认的箭头样式--> 15 <li style="cursor:pointer" id="user_{{ k }}" ondblclick="vote({{ k }});"> 16 ID:{{k}},name:{{v.name}},count:<span>{{v.count}}</span> 17 </li> 18 19 {% endfor %} 20 </ul> 21 <hr> 22 23 24 <script src="/static/jquery-3.3.1.min.js"></script> 25 <script> 26 $(function(){ 27 fetch_count(); 28 }); 29 function fetch_count(){ 30 $.ajax({ 31 url:'/get_count', 32 type:'GET', 33 dataType:'JSON', 34 success:function(arg){ 35 if (arg.status){ 36 var gid='#user_'+arg.data.gid; 37 $(gid).find('span').text(arg.data.count); 38 }else{ 39 } 40 fetch_count(); 41 42 } 43 44 }) 45 } 46 47 function vote(gid){ 48 $.ajax({ 49 url:'/vote', 50 type:'POST', 51 data:{obj:gid}, 52 dataType:'JSON', 53 success:function(arg){ 54 55 } 56 57 }) 58 } 59 </script> 60 </body> 61 </html>
py文件
1 from flask import Flask, request, render_template, redirect, session, jsonify 2 import uuid 3 import queue 4 import redis, json 5 6 app = Flask(__name__) 7 app.secret_key = 'asdfsg' 8 # vote_conn = redis.Redis(host='127.0.0.1', port=6379) 9 redis_pool = redis.ConnectionPool(host='127.0.0.1', port=6379) 10 vote_conn = redis.Redis(connection_pool=redis_pool) 11 12 13 # USER_QUEUE = {} 14 # 这是模拟数据库,从数据库中取出数据 15 std_li = { 16 '1': {'name': 'peter', 'count': 0}, 17 '2': {'name': 'fred', 'count': 0}, 18 } 19 20 @app.before_request 21 def check_login(): 22 if request.path == '/login': 23 return None 24 25 user = session.get('user_form') 26 if not user: 27 return redirect('/login') 28 29 30 @app.route('/login', methods=['GET', 'POST']) 31 def login(): 32 if request.method == 'GET': 33 return render_template('login.html') 34 35 else: 36 user = request.form.get('user') 37 pwd = request.form.get('pwd') 38 uid = str(uuid.uuid4()) 39 # USER_QUEUE[uid] = queue.Queue() 40 vote_conn.lpush('hell', uid) # 这里的key是自定义随便写的,我们把数据存入到这里的键uid_li里面,要取数据也要从这里取出来 41 session['user_form'] = {'uid': uid, 'name': user} 42 return redirect('/index') 43 44 45 @app.route('/index') 46 def index(): 47 return render_template('index.html', obj=std_li) 48 49 50 @app.route('/get_count') 51 def get_count(): 52 ret = {'status': True, 'data': None} 53 uid = session['user_form']['uid'] 54 q = vote_conn.brpop(uid,timeout=10) 55 # q = USER_QUEUE[uid] 56 if not q: 57 ret['status'] = False 58 59 else: 60 q_str = str(q[1], encoding='utf8') 61 q_dic = json.loads(q_str) # 这里是对数据类型进行处理,把字节转换成字符串然后进行序列化用于数据传输 62 ret['data'] = q_dic 63 # try: 64 # data = q.get(timeout=5) 65 # print('data', data) # data {'gid': '1', 'count': 1} 66 # ret['data'] = data 67 # print('get_count', ret) # get_count {'status': True, 'data': {'gid': '1', 'count': 1}} 68 # except queue.Empty as e: 69 # ret['status'] = False 70 return jsonify(ret) 71 72 73 @app.route('/vote', methods=['POST']) 74 def vote(): 75 """ 76 接收用户请求,把请求的数据结果放到我们的std_li字典里面去 77 :return: 78 """ 79 gid = request.form.get('obj') 80 old = std_li[gid]['count'] 81 new = old + 1 82 std_li[gid]['count'] = new 83 data = json.dumps({'gid': gid, 'count': new}) 84 # for obj in USER_QUEUE.values(): 85 # obj.put(data) 86 li = vote_conn.lrange('hell', 0, vote_conn.llen('hell')) # 这里我们是从上面的login里面设置的keyuid_li 87 # 里面取出数据,这个key和上面的key需要对应上 88 for obj in li: 89 vote_conn.lpush(obj, data) 90 return 'ok' 91 92 93 if __name__ == '__main__': 94 app.run(host='192.168.12.9', threaded=True)

浙公网安备 33010602011771号