Flask框架運(yùn)用Ajax實(shí)現(xiàn)輪詢動(dòng)態(tài)繪圖
Ajax是異步JavaScript和XML可用于前后端交互,在之前《Flask 框架:運(yùn)用Ajax實(shí)現(xiàn)數(shù)據(jù)交互》簡(jiǎn)單實(shí)現(xiàn)了前后端交互,本章將通過(guò)Ajax
輪詢獲取后端的數(shù)據(jù),前臺(tái)使用echart
繪圖庫(kù)進(jìn)行圖形的生成與展示,后臺(tái)通過(guò)render_template
方法返回一串JSON數(shù)據(jù)集,前臺(tái)收到后將其應(yīng)用到繪圖庫(kù)上,實(shí)現(xiàn)動(dòng)態(tài)監(jiān)控內(nèi)存利用率的這個(gè)功能。
首先LyShark
先來(lái)演示一下前端如何運(yùn)用AJAX實(shí)現(xiàn)交互,通過(guò)$.ajax
定義ajax開(kāi)始標(biāo)志,并指定url,type,datetype
等信息,通過(guò)setInterval
設(shè)置一個(gè)1000毫秒的定時(shí)器,每隔一段時(shí)間則去后端取數(shù)據(jù)。
<!-- # 署名權(quán) # right to sign one's name on a piece of work # PowerBy: LyShark # Email: me@lyshark.com --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/echarts/5.3.0/echarts.min.js"></script> </head> <body> <!--設(shè)定一個(gè)定時(shí)器,每隔1000毫秒向后端發(fā)送請(qǐng)求--> <script type="text/javascript"> $( function () { fetchData(); setInterval(fetchData, 1000); } ); function fetchData(){ $.ajax({ url:"/", type:"POST", dataType: 'json', success:function (recv) { console.log("[lyshark.com] 獲取到時(shí)間:" + recv.response[0]); console.log("[lyshark.com] 獲取到數(shù)據(jù):" + recv.response[1]); } }) } </script> </body>
后端只需要根據(jù)前端需要的格式返回系統(tǒng)中的CPU利用率(此處模擬),并使用json.dumps({"response":[times,data]})
推送到前端即可。
# 署名權(quán) # right to sign one's name on a piece of work # PowerBy: LyShark # Email: me@lyshark.com from flask import Flask,render_template,request import json,time,random async_mode = None app = Flask(import_name=__name__, static_url_path='/python', # 配置靜態(tài)文件的訪問(wèn)url前綴 static_folder='static', # 配置靜態(tài)文件的文件夾 template_folder='templates') # 配置模板文件的文件夾 @app.route('/',methods=['POST','GET']) def index(): if request.method == "GET": return render_template("index.html") elif request.method == "POST": times = time.strftime("%M:%S", time.localtime()) data = [random.randint(1,100)] return json.dumps({"response":[times,data]}) if __name__ == '__main__': app.run()
運(yùn)行這段代碼,然后打開(kāi)控制臺(tái),則可以看到如下數(shù)據(jù),前臺(tái)會(huì)每隔一秒向后端請(qǐng)求數(shù)據(jù);
如果上方繪制可以被正確執(zhí)行,那么想要實(shí)現(xiàn)輪詢繪圖只需要封裝實(shí)現(xiàn)一個(gè)update()
自定義繪圖函數(shù),該函數(shù)內(nèi)將得到的數(shù)據(jù)統(tǒng)一放入到數(shù)組內(nèi),并調(diào)用封裝好的display()
函數(shù),將數(shù)據(jù)繪制到前臺(tái)。
<!-- # 署名權(quán) # right to sign one's name on a piece of work # PowerBy: LyShark # Email: me@lyshark.com --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/echarts/5.3.0/echarts.min.js"></script> </head> <body> <!--定義繪圖區(qū)域--> <div id="main" style="height:300px;width:80%;border:1px solid #eecc11;padding:10px;"></div> <!--調(diào)用百度的繪圖庫(kù),進(jìn)行圖片的繪制工作.--> <script type="text/javascript" charset="UTF-8"> var display = function(time,cpu) { var main = echarts.init(document.getElementById(("main"))); var option = { xAxis: { boundaryGap:false, boundaryGap:false, type: 'category', data: time }, yAxis: { type: 'value' }, series: [{ type: 'line', areaStyle:{}, data: cpu }] }; main.setOption(option,true); }; </script> <!--update()函數(shù)具體執(zhí)行的任務(wù),其主要只保留前十條數(shù)據(jù).--> <script type="text/javascript" charset="UTF-8"> // 負(fù)責(zé)對(duì)參數(shù)的解析 var time =["","","","","","","","","",""]; var cpu = [0,0,0,0,0,0,0,0,0,0]; var update = function(recv){ time.push(recv.response[0]); cpu.push(parseFloat(recv.response[1])); if(time.length >=10){ time.shift(); cpu.shift(); console.log("處理后的時(shí)間數(shù)據(jù):" + time); console.log("處理后的CPU數(shù)據(jù):" + cpu); display(time,cpu) // 調(diào)用繪圖函數(shù) } }; </script> <!--設(shè)定一個(gè)定時(shí)器,每隔1000毫秒向后端發(fā)送請(qǐng)求--> <script type="text/javascript"> $( function () { fetchData(); setInterval(fetchData, 1000); } ); function fetchData(){ $.ajax({ url:"/", type:"POST", dataType: 'json', success:function (recv) { console.log("獲取到時(shí)間:" + recv.response[0]); console.log("獲取到數(shù)據(jù):" + recv.response[1]); // 傳遞給處理函數(shù) update(recv) } }) } </script> </body>
對(duì)于后臺(tái)來(lái)說(shuō),我們不需要做任何變更,因?yàn)橹灰覀冏裱祷豃SON的格式即可,運(yùn)行替換后的程序,我們可以看到控制臺(tái)會(huì)出現(xiàn)以下參數(shù);
這就標(biāo)志著接收的數(shù)據(jù)是正確的,我們來(lái)看下最終繪制效果;
當(dāng)然有時(shí)候我們需要返回多個(gè)圖形,而不是一個(gè),運(yùn)用輪詢同樣可以實(shí)現(xiàn),如下案例中將兩個(gè)儀表盤合并在了一起,并通過(guò)一個(gè)接口實(shí)現(xiàn)了數(shù)據(jù)的輪詢,相比上方代碼變化并不大。
<!-- # 署名權(quán) # right to sign one's name on a piece of work # PowerBy: LyShark # Email: me@lyshark.com --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/echarts/5.3.0/echarts.min.js"></script> </head> <body> <!--定義繪圖區(qū)域--> <div id="cpuChart" style="width: 20%; height: 300px; border: 1px solid #dddddd; float:left; margin-right: 8px;"></div> <div id="memChart" style="width: 20%; height: 300px; border: 1px solid #dddddd; float:left; margin-right: 8px;"></div> <!--封裝方法,一次性繪制兩個(gè)圖形--> <script type="text/javascript" charset="UTF-8"> var display = function(cpu,mem) { var cpuChart = echarts.init(document.getElementById("cpuChart")); var option = { series: [ { name: 'Pressure', type: 'gauge', progress: { show: true }, detail: {formatter: '{value} %',fontSize: 12}, data: [{value: cpu, name: 'CPU負(fù)載'}] } ] };cpuChart.setOption(option, true); var memChart = echarts.init(document.getElementById("memChart")); var option = { series: [ { name: 'Pressure', type: 'gauge', progress: { show: true }, detail: {formatter: '{value} %',fontSize: 12}, data: [{value: mem, name: '內(nèi)存利用率'}] } ] };memChart.setOption(option, true); }; </script> <!--定義輪巡--> <script type="text/javascript"> $( function () { fetchData(); setInterval(fetchData, 100); } ); function fetchData(){ $.ajax({ url:"/", type:"POST", dataType: 'json', success:function (recv) { display(recv.response[0],recv.response[1]); } }) } </script> </body>
后端部分只需要稍微小改一下,將json.dumps({"response":[cpu,mem]})
返回時(shí)指定兩個(gè)參數(shù)即可。
# 署名權(quán) # right to sign one's name on a piece of work # PowerBy: LyShark # Email: me@lyshark.com from flask import Flask,render_template,request import json,time,random async_mode = None app = Flask(import_name=__name__, static_url_path='/python', # 配置靜態(tài)文件的訪問(wèn)url前綴 static_folder='static', # 配置靜態(tài)文件的文件夾 template_folder='templates') # 配置模板文件的文件夾 @app.route('/',methods=['POST','GET']) def index(): if request.method == "GET": return render_template("index.html") elif request.method == "POST": times = time.strftime("%M:%S", time.localtime()) mem = random.randint(1,100) cpu = random.randint(1,100) return json.dumps({"response":[cpu,mem]}) if __name__ == '__main__': app.run()
框架運(yùn)行后,在前端可以看到兩個(gè)儀表盤分別顯示不同的參數(shù);
到此這篇關(guān)于Flask框架運(yùn)用Ajax實(shí)現(xiàn)輪詢動(dòng)態(tài)繪圖的文章就介紹到這了,更多相關(guān)Flask Ajax輪詢動(dòng)態(tài)繪圖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pip已經(jīng)安裝好第三方庫(kù)但pycharm中import時(shí)還是標(biāo)紅的解決方案
這篇文章主要介紹了python中pip已經(jīng)安裝好第三方庫(kù)但pycharm中import時(shí)還是標(biāo)紅的問(wèn)題,本文給大家分享解決方法,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10Python命令行參數(shù)解析模塊getopt使用實(shí)例
這篇文章主要介紹了Python命令行參數(shù)解析模塊getopt使用實(shí)例,本文講解了使用語(yǔ)法格式、短選項(xiàng)參數(shù)實(shí)例、長(zhǎng)選項(xiàng)參數(shù)實(shí)例等內(nèi)容,需要的朋友可以參考下2015-04-04python環(huán)境中的概念conda中與環(huán)境相關(guān)指令操作
這篇文章主要介紹了python環(huán)境中的概念conda中與環(huán)境相關(guān)指令操作,虛擬環(huán)境是從電腦獨(dú)立開(kāi)辟出來(lái)的環(huán)境,文章介紹了相關(guān)概念,需要的朋友可以參考下2023-03-03Python Pillow.Image 圖像保存和參數(shù)選擇方式
今天小編就為大家分享一篇Python Pillow.Image 圖像保存和參數(shù)選擇方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01在Django的視圖中使用數(shù)據(jù)庫(kù)查詢的方法
這篇文章主要介紹了在Django的視圖中使用數(shù)據(jù)庫(kù)查詢的方法,是Python的Django框架使用的基礎(chǔ)操作,需要的朋友可以參考下2015-07-07