Flask框架運用Ajax實現(xiàn)輪詢動態(tài)繪圖
Ajax是異步JavaScript和XML可用于前后端交互,在之前《Flask 框架:運用Ajax實現(xiàn)數(shù)據(jù)交互》簡單實現(xiàn)了前后端交互,本章將通過Ajax輪詢獲取后端的數(shù)據(jù),前臺使用echart繪圖庫進行圖形的生成與展示,后臺通過render_template方法返回一串JSON數(shù)據(jù)集,前臺收到后將其應(yīng)用到繪圖庫上,實現(xiàn)動態(tài)監(jiān)控內(nèi)存利用率的這個功能。
首先LyShark先來演示一下前端如何運用AJAX實現(xiàn)交互,通過$.ajax定義ajax開始標志,并指定url,type,datetype等信息,通過setInterval設(shè)置一個1000毫秒的定時器,每隔一段時間則去后端取數(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è)定一個定時器,每隔1000毫秒向后端發(fā)送請求-->
<script type="text/javascript">
$(
function () {
fetchData();
setInterval(fetchData, 1000);
}
);
function fetchData(){
$.ajax({
url:"/",
type:"POST",
dataType: 'json',
success:function (recv) {
console.log("[lyshark.com] 獲取到時間:" + 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)文件的訪問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()
運行這段代碼,然后打開控制臺,則可以看到如下數(shù)據(jù),前臺會每隔一秒向后端請求數(shù)據(jù);

如果上方繪制可以被正確執(zhí)行,那么想要實現(xiàn)輪詢繪圖只需要封裝實現(xiàn)一個update()自定義繪圖函數(shù),該函數(shù)內(nèi)將得到的數(shù)據(jù)統(tǒng)一放入到數(shù)組內(nèi),并調(diào)用封裝好的display()函數(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>
<!--定義繪圖區(qū)域-->
<div id="main" style="height:300px;width:80%;border:1px solid #eecc11;padding:10px;"></div>
<!--調(diào)用百度的繪圖庫,進行圖片的繪制工作.-->
<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">
// 負責對參數(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ù)據(jù):" + time);
console.log("處理后的CPU數(shù)據(jù):" + cpu);
display(time,cpu) // 調(diào)用繪圖函數(shù)
}
};
</script>
<!--設(shè)定一個定時器,每隔1000毫秒向后端發(fā)送請求-->
<script type="text/javascript">
$(
function () {
fetchData();
setInterval(fetchData, 1000);
}
);
function fetchData(){
$.ajax({
url:"/",
type:"POST",
dataType: 'json',
success:function (recv) {
console.log("獲取到時間:" + recv.response[0]);
console.log("獲取到數(shù)據(jù):" + recv.response[1]);
// 傳遞給處理函數(shù)
update(recv)
}
})
}
</script>
</body>
對于后臺來說,我們不需要做任何變更,因為只要我們遵循返回JSON的格式即可,運行替換后的程序,我們可以看到控制臺會出現(xiàn)以下參數(shù);

這就標志著接收的數(shù)據(jù)是正確的,我們來看下最終繪制效果;

當然有時候我們需要返回多個圖形,而不是一個,運用輪詢同樣可以實現(xiàn),如下案例中將兩個儀表盤合并在了一起,并通過一個接口實現(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>
<!--封裝方法,一次性繪制兩個圖形-->
<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負載'}]
}
]
};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ù)即可。
# 署名權(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)文件的訪問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()
框架運行后,在前端可以看到兩個儀表盤分別顯示不同的參數(shù);

到此這篇關(guān)于Flask框架運用Ajax實現(xiàn)輪詢動態(tài)繪圖的文章就介紹到這了,更多相關(guān)Flask Ajax輪詢動態(tài)繪圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pip已經(jīng)安裝好第三方庫但pycharm中import時還是標紅的解決方案
這篇文章主要介紹了python中pip已經(jīng)安裝好第三方庫但pycharm中import時還是標紅的問題,本文給大家分享解決方法,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
Python命令行參數(shù)解析模塊getopt使用實例
這篇文章主要介紹了Python命令行參數(shù)解析模塊getopt使用實例,本文講解了使用語法格式、短選項參數(shù)實例、長選項參數(shù)實例等內(nèi)容,需要的朋友可以參考下2015-04-04
python環(huán)境中的概念conda中與環(huán)境相關(guān)指令操作
這篇文章主要介紹了python環(huán)境中的概念conda中與環(huán)境相關(guān)指令操作,虛擬環(huán)境是從電腦獨立開辟出來的環(huán)境,文章介紹了相關(guān)概念,需要的朋友可以參考下2023-03-03
Python Pillow.Image 圖像保存和參數(shù)選擇方式
今天小編就為大家分享一篇Python Pillow.Image 圖像保存和參數(shù)選擇方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
在Django的視圖中使用數(shù)據(jù)庫查詢的方法
這篇文章主要介紹了在Django的視圖中使用數(shù)據(jù)庫查詢的方法,是Python的Django框架使用的基礎(chǔ)操作,需要的朋友可以參考下2015-07-07

