在flask中使用websocket-实时消息推送
生活随笔
收集整理的這篇文章主要介紹了
在flask中使用websocket-实时消息推送
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
- flask默認(rèn)使用wsgi支持http協(xié)議,如需使用websocket需要安裝gevent-websocket模塊,http,websocket協(xié)議都可以支持
Django應(yīng)用:channel
Tornado應(yīng)用:自己有
app.py
from flask import Flask,request,render_template,redirect,session import uuid from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer import jsonapp = Flask(__name__) app.secret_key = ';lkjnfdidiclsjek'GENTIEMAN = {'1':{'name':'鋼彈','count':0},'2':{'name':'鐵錘','count':0},'3':{'name':'閆帥','count':0}, }WEBSOCKET_DICT = {}@app.before_request def before_reuqest():if request.path == '/login':return Noneuser_info = session.get('user_info')if user_info:return Nonereturn redirect('login')@app.route('/login',methods=['GET','POST']) def login():if request.method == 'GET':return render_template('login.html')else:uid = str(uuid.uuid4())session['user_info'] = {'id':uid,'name':request.form.get('user')}return redirect('/index')@app.route('/index') def index():return render_template('index.html',users=GENTIEMAN)@app.route('/message') def message():# 1. 判斷是否為Websocket請求,http不包含wsgi.websocketws = request.environ.get('wsgi.websocket')if not ws:return 'use websocket'# 此處連接成功current_user_id = session['user_info']['id']WEBSOCKET_DICT[current_user_id] = wswhile True:# 2. 等待用戶發(fā)送消息,并接受message = ws.receive() # 投票對應(yīng)的ID# 關(guān)閉 mesaage = Noneif not message:del WEBSOCKET_DICT[current_user_id]break# 3. 獲取用戶要投票的ID,并+1old = GENTIEMAN[message]['count']new = old + 1GENTIEMAN[message]['count'] = newdata = {'user_id':message,'count':new,'type':'vote'}# 給所有客戶端推送消息for conn in WEBSOCKET_DICT.values():conn.send(json.dumps(data))return '完畢'@app.route('/notify') def notify():data = {'data':'訂單生成','type':'alert'}for conn in WEBSOCKET_DICT.values():conn.send(json.dumps(data))return '完畢'if __name__ == '__main__':# 如果是http請求走app使用原有的wsgi處理,如果是websocket請求走WebSocketHandler處理http_server = WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)http_server.serve_forever()index.html
<body><h1>投票系統(tǒng):參與投票的人</h1><ul>{% for k,v in users.items() %}<li id="user_{{k}}" οndblclick="vote('{{k}}')">{{v.name}} <span>{{v.count}}</span> </li>{% endfor %}</ul><script src="{{ url_for('static',filename='jquery-3.3.1.min.js')}}"></script><script>var socket = new WebSocket("ws://127.0.0.1:5000/message");socket.onmessage = function (event) {/* 服務(wù)器端向客戶端發(fā)送數(shù)據(jù)時,自動執(zhí)行 */var response = JSON.parse(event.data); // {'user':1,'count':new}if(response.type == 'vote'){var nid = '#user_' + response.user_id;$(nid).find('span').text(response.count)}else{alert(response.data);}};/*我要給某人投票*/function vote(id) {socket.send(id);}</script> </body>?
login.html
<body> <form method="post"><input type="text" name="user"><input type="submit" value="提交"> </form> </body>?
轉(zhuǎn)載于:https://www.cnblogs.com/sunlong88/p/9623707.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的在flask中使用websocket-实时消息推送的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。