flask
websocket
websocket作為在html5後引入的功能,有別於傳統ajax需要不斷刷新頁面,websocket能夠讓瀏覽器和server以直接建立socket的方式更新瀏覽器顯示的資料,本節以flask-websocketio作為示範。
環境:
首先在你的python虛擬環境中安裝flask-socketio
建立index.html,在header 中加入下列script
var socket = io.connect()
:建立socketio連線
接著可以看到我們建立一個status_response
的socket event來監聽事件,當flask發送事件時<div>
tag就會append收到的資料和當下的時間。
接下來讓我們完成flask的server端程式
當使用socketio時,需要將環境變數中的export FLASK_ENV=development
移除
執行flask run
就可以看到結果了,每當/status
被呼叫時index.html
的status
div tag就會新增一行資料。