Django 通过Ajax接口实现前后端数据交互功能,通过Ajax实现当用户输入要查询的数据时,发送到后端,后端处理后推送到前端,前端直接绘制图形。
首先实现Ajax前后端简单交互功能,我们直接在templates
新增一个index.html
并在代码中调用echarts前端绘图库.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.lyshark.com/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.lyshark.com/echarts/5.0.0/echarts.min.js" type="text/javascript"></script>
</head>
<body>
<div id="main" style="height:400px;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
$.ajax({
type: "get",
url: "/_ajax",
dataType: "json",
success: function (data) {
var option = {
title: {
left: 'center',
text: '测试数据'
},
tooltip: {},
xAxis: {
data: data.key
},
yAxis: {},
series: [{
name: '数量',
type: 'bar',
data: data.value
}]
};
myChart.setOption(option);
},
error: function () {
alert('Error: ajax')
}
})
</script>
</body>
</html>
接着我们在urls.py
中新增一个路由,该路由我们命名为echart
指向views.echart
视图。
from django.contrib import admin
from django.urls import path
from MyWeb import views
urlpatterns = [
path('echart',views.echart),
path('_ajax',views._ajax)
]
最后转到views.py
中实现echart
视图与_ajax
两个视图函数.
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
# 调用绘图函数
def echart(request):
return render(request,"index.html")
# 实现参数传递接口
def _ajax(request):
send_json = {
"key": [1,2,3,4,5,6,7,8],
"value": [1,2,3,4,5,6,7,8]
}
return JsonResponse(send_json)
此时当用户访问index.html
页面时会自动路由到echart()
函数上,该函数会去_ajax
中请求数据,并返回到前端页面.
我们继续完善,查询功能,实现当用户输入要查询的数据时,通过Ajax发送到后端,处理后返回前端并绘图。
首先在MyWeb
项目的models.py
中创建数据模型,数据库名称为cpu_load_avg
直接更新数据库参数即可.
from django.db import models
# 创建CPU负载表结构
class cpu_load_avg(models.Model):
uuid = models.AutoField(primary_key = True)
address = models.CharField(max_length=64)
times = models.CharField(max_length=64)
load5 = models.CharField(max_length=64)
load10 = models.CharField(max_length=64)
load15 = models.CharField(max_length=64)
直接执行建库建表命令.
python manage.py makemigrations
python manage.py migrate
接着,我们通过下面的脚本,监控系统的负载情况并插入到数据库,这里我们等待十分钟左右,当前时间为15点48分。
import sqlite3
import time,psutil,datetime
def GetCPU_Load(addr):
times = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M")
cpu = psutil.cpu_percent(interval=None,percpu=True)
dict = {'address': addr,'times': times,'load5': cpu[0],'load10': cpu[1],'load15':cpu[2]}
return dict
if __name__ == "__main__":
conn = sqlite3.connect("db.sqlite3")
cursor = conn.cursor()
while True:
dict = GetCPU_Load("127.0.0.1")
insert = 'insert into MyWeb_cpu_load_avg(address,times,load5,load10,load15) values("{}","{}","{}","{}","{}")'.
format(dict["address"],dict["times"],dict["load5"],dict["load10"],dict["load15"])
print(insert)
cursor.execute(insert)
conn.commit()
time.sleep(1)
这个脚本运行后会采集CPU负载信息,通过以下格式存储到数据库内。
此时我收集了 15点48分 - 15点-55分 之间的CPU图形数据到数据库中.
接着来创建我们的index.html
前端页面,代码不难,我倒是写了一段时间.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.lyshark.com/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.lyshark.com/echarts/5.0.0/echarts.min.js" type="text/javascript"></script>
</head>
<body>
<!--提交表格数据-->
<form action="/_ajax/" method="post" id="myForm">
<p>主机地址: <input type="text" name="address" placeholder="输入主机IP地址"></p>
<p>开始时间: <input type="datetime-local" name="start_data" /></p>
<p>结束时间: <input type="datetime-local" name="end_data" /></p>
<select name="select">
<option value="load5">五分钟负载</option>
<option value="load10">十分钟负载</option>
<option value="load15">十五分钟负载</option>
</select>
<input name="btn" id="btn" type="button" value="查询数据"></input>
</form>
<!--绘图区域-->
<div id="main" style=" 100%;height:450px;border:1px solid #dddddd;float: left;margin-top: 10px;"></div>
<!--绘图函数实现流程-->
<script type="text/javascript" charset="UTF-8">
var create_graphical = function(time,cpu){
var myChart_cpu = echarts.init(document.getElementById('main'));
myChart_cpu.setOption({
tooltip: {},
xAxis: {
data: []
},
yAxis: {},
series: [{
name: 'cpu',
type: 'line',
data: []
}]
});
// 下方就是给指定字段填充数据
myChart_cpu.setOption({
xAxis: {
data: time
},
series: [{
name: 'cpu',
data: cpu
}]
});
};
</script>
<!--点击查询后执行的Ajax操作-->
<script type="text/javascript">
$("#btn").click(function(){
$.ajax({
url: "./_ajax/",
type: "POST",
data: $("#myForm").serialize(),
success:function (data) {
var data = JSON.parse(data);
create_graphical(data.status,data.status)
}
})
})
</script>
</body>
</html>
接着在urls.py
中增加两个路由记录.
from django.contrib import admin
from django.urls import path
from MyWeb import views
urlpatterns = [
path('admin/', admin.site.urls),
path('indexa',views.indexa),
path('_ajax/',views._ajax),
]
后端views.py
视图,只需要根据用户的选择做特定字段的查询工作即可.
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
import json
from MyWeb import models
# 调用绘图函数
def echart(request):
return render(request,"index.html")
# 调用主页
def indexa(request):
return render(request,"index.html")
# 实现参数传递接口
def _ajax(request):
if request.method == "POST":
cpu_load = []
address = request.POST.get("address")
start_data = request.POST.get("start_data")
end_data = request.POST.get("end_data")
select = request.POST.get("select")
ret = models.cpu_load_avg.objects.raw('select * from MyWeb_cpu_load_avg where Address == "{}" and Times>="{}" and Times <="{}";'.
format(address,start_data,end_data))
if select == "load5":
for item in ret:
cpu_load.append(float(item.load5))
return HttpResponse(json.dumps({"status": cpu_load }))
elif select == "load10":
for item in ret:
cpu_load.append(float(item.load10))
return HttpResponse(json.dumps({"status": cpu_load}))
elif select == "load15":
for item in ret:
cpu_load.append(float(item.load15))
return HttpResponse(json.dumps({"status": cpu_load}))
return render(request,"index.html")
最后,我们输入需要查询的地址以及该地址某个时间段的负载情况,即可查询到图形信息。