Try   HackMD

Flask實作_websocket

tags: flask websocket

前言

websocket作為在html5後引入的功能,有別於傳統ajax需要不斷刷新頁面,websocket能夠讓瀏覽器和server以直接建立socket的方式更新瀏覽器顯示的資料,本節以flask-websocketio作為示範。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

flask-socket-io官方文件

實做內容

環境:

pipenv, version 9.0.1
python3.7
ubuntu 18.04

首先在你的python虛擬環境中安裝flask-socketio

pip install flask-socketio

建立index.html,在header 中加入下列script

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ var socket = io.connect(); socket.on('status_response', function(msg) { var date = new Date(); $('#status').append('<p>status: ' + msg.data + "Time:"+ date+ '</p>'); }); }); </script> <!-- 在body中加入status的div tag--> <div id="status"></div>

var socket = io.connect():建立socketio連線
接著可以看到我們建立一個status_response的socket event來監聽事件,當flask發送事件時<div>tag就會append收到的資料和當下的時間。

接下來讓我們完成flask的server端程式

from flask import Flask, request, abort, render_template, jsonify from flask_socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route("/status", methods=['GET']) def upload(): if not request.json: abort(400) d = request.json.get("data", 0) print("receive data:{}".format(d)) # do something # 回傳給前端 socketio.emit('status_response', {'data': d}) return jsonify( {"response": "ok"} ) @app.route("/") def home(): return render_template('index.html', async_mode=socketio.async_mode) if __name__ == "__main__": socketio.run(app, debug=True)

當使用socketio時,需要將環境變數中的export FLASK_ENV=development移除

執行flask run就可以看到結果了,每當/status被呼叫時index.htmlstatus div tag就會新增一行資料。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →