Django 实现自动化运维后台

Python
291
0
0
2023-02-13
标签   Django

layui 框架与BootCSS框架相似都属于前端美化框架,区别在于BootCSS更加专业,而LayUI则更多的是面向于后端开发者,所以在组织形式上毅然采用了几年前的以浏览器为宿主的类 AMD 模块管理方式,却又并非受限于 CommonJS 的那些条条框框,它拥有自己的模式,更加轻量和简单。

下面的页面作为基模板,取名为 base.html 后期子模版,全部继承它。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自动化监控平台</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://www.blib.cn/cdn/layui/css/layui.css">
    <script type="text/javascript" src="https://www.blib.cn/cdn/echarts.js"></script>
    <script type="text/javascript" src="https://www.blib.cn/cdn/jquery.js"></script>
</head>

{% block css %}
    <style>
        .layui-layout-admin .layui-body {
            background-color: #eee;
            padding-left: 15px;
            padding-top: 15px;
            padding-right: 15px;
        }
        .layui-layout-admin .layui-logo {
            font-size: 20px;
        }
        .layui-layout-admin .layui-footer {
            background-color: rgba(242, 242, 242, 0);
            text-align:center;
        }
    </style>
{% endblock %}

<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
  <div class="layui-header">
    <div class="layui-logo"> <i class="layui-icon layui-icon-component" style="font-size: 35px;"></i> 自动化监控平台</div>
    <!-- 头部区域 -->
    <ul class="layui-nav layui-layout-left ">
      <li class="layui-nav-item layui-hide-xs" lay-unselect="">
        <a href="javascript:;" layadmin-event="fullscreen">
          <i class="layui-icon layui-icon-screen-full"></i>
        </a>
      </li>
      <li class="layui-nav-item"><a href="/">仪表盘</a></li>
      <li class="layui-nav-item">
            <a href="javascript:;">安全配置</a>
            <dl class="layui-nav-child">
                  <dd><a href="">邮件管理</a></dd>
                  <dd><a href="">消息管理</a></dd>
            </dl>
      </li>
    </ul>

    <!-- 右上角的基本资料配置区域-->
    <ul class="layui-nav layui-layout-right">
      <li class="layui-nav-item">
        <a href="javascript:;">
          <img src="https://www.blib.cn/cdn/head.jpg" class="layui-nav-img"> LyShark
        </a>
        <dl class="layui-nav-child">
          <dd><a href="">安全设置</a></dd>
          <dd><a href="">用户注销</a></dd>
        </dl>
      </li>
    </ul>
  </div>

  <div class="layui-side layui-bg-black">
    <div class="layui-side-scroll">
      <!-- 左侧导航区域 -->
      <ul class="layui-nav layui-nav-tree"  lay-filter="test">
        <li class="layui-nav-item layui-nav-itemed layui-this">
          <a class="" href="/"><i class="layui-icon layui-icon-theme"></i> 仪表盘</a>
        </li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-table"></i> 主机管理</a></li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-chart"></i> 动态监控</a></li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-time"></i> 图形查询</a></li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-search"></i> 日志检索</a></li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-next"></i> 远程命令</a></li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-set"></i> 系统设置</a></li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-auz"></i></i> 授权管理</a></li>
      </ul>
    </div>
  </div>

  <!-- 内容主体区域 -->
  <div class="layui-body">
      {% block content %}
      {% endblock %}
  </div>
    <div class="layui-footer"> C 2018 -2020 版权所有 LyShark 保留所有权利</div>
  </div>
    <script src="https://www.blib.cn/cdn/layui/layui.js"></script>
    <script>
    layui.use('element', function(){
      var element = layui.element;

    });
    </script>
</body>
</html>

创建仪表盘子页面,此处就叫 main.html 这里直接继承base.html

{% extends "base.html" %}
{% block content %}
    <!-- 系统图形统计,用于统计本机CPU利用率,内存利用率,与磁盘等数据,后期添加-->
<div class="layui-card" style="width:100%; height: 30%;float:left;">
  <div class="layui-card-header">当前系统状态</div>
        <div class="layui-card-body">
            等待添加统计图形功能。
        <br>
  </div>
</div>

<div class="layui-card" style="width:49%; height: 60%;float:left;">
    <div class="layui-card-header">CPU利用率</div>
        <div class="layui-card-body">
            等待添加统计图形功能。
        <br>
    </div>
</div>
<div class="layui-card" style="width:49%; height: 60%;float:right;">
    <div class="layui-card-header">内存利用率</div>
    <div class="layui-card-body">
        等待添加统计图形功能。
    <br>
    </div>
</div>
{% endblock %}

urls.py

from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("",views.main)
]

img

上面的代码a标签如果被填上待跳转路径就会出现,跳转虽然实现了,但是a标签无法高亮,解决的办法这里我想到了一个比较笨的方法。

    var Arry  = ["/host/","/logs/"];
    for(var x=0;x<10;x++)
    {
        var log = window.location.pathname;
        if (Arry[x] == log){
            $(".layui-side-scroll li").removeClass("layui-nav-itemed")[0];
            $(".layui-side-scroll li").removeClass("layui-this")[0];
            $(".layui-side-scroll li").next().eq(x).addClass("layui-this");
            $(".layui-side-scroll li").next().eq(x).addClass("layui-nav-itemed");
        }
    }

img

最终的效果是这样的。

img

我们继续完善这个main.html 页面,仪表盘用于统计本机数据。

{% extends "base.html" %}
{% block content %}
<style>
.layui-badge {
    position: absolute;
    top: 50%;
    margin-top: -9px;
    right: 15px;
    }
.title-color {
    font-style: normal;
    font-size: 30px;
    font-weight: 300;
    color: #009688;
}
.layui-span-color {
    font-size: 14px;
    position: absolute;
    right: 15px;
}
</style>
<!--------------------------------------------------------------------------------------------------------------->
<!-- 格栅,四个面板,之间相隔一定的距离-->
<div class="layui-row layui-col-space15">

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">在线用户
              <span class="layui-badge layui-bg-blue">Local User</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">1 Users</p><br>
              <p>
              总活跃用户<span class="layui-span-color">1 <i class="layui-inline layui-icon layui-icon-flag"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">本机进程数
              <span class="layui-badge layui-bg-green">Process ID</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">248 Process</p><br>
              <p>
              总活进程数<span class="layui-span-color">248 <i class="layui-inline layui-icon layui-icon-face-smile-b"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">管理主机数量
              <span class="layui-badge layui-bg-red"> Host Count</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">256 Hosting</p><br>
              <p>
              管理主机数量<span class="layui-span-color">248 <i class="layui-inline layui-icon layui-icon-user"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">当前活跃会话
              <span class="layui-badge layui-bg-orange"> Local Sesion</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">1 Session</p><br>
              <p>
              活跃的会话<span class="layui-span-color">1 <i class="layui-inline layui-icon layui-icon-user"></i></span>
              </p>
          </div>
        </div>
    </div>
</div>
<br>
<!--------------------------------------------------------------------------------------------------------------->
<!-- 系统图形统计,用于统计本机CPU利用率,内存利用率,与磁盘等数据,后期添加-->
<div class="layui-card" style="width:100%; height: 30%;float:left;">
  <div class="layui-card-header">系统CPU负载</div>
        <div class="layui-card-body">
            等待添加统计图形功能。
        <br>
  </div>
</div>

<div class="layui-card" style="width:49%; height: 60%;float:left;">
    <div class="layui-card-header">内存利用率</div>
        <div class="layui-card-body">
            等待添加统计图形功能。
        <br>
    </div>
</div>

<div class="layui-card" style="width:49%; height: 60%;float:right;">
    <div class="layui-card-header">网络数据包</div>
    <div class="layui-card-body">
        等待添加统计图形功能。
    <br>
    </div>
</div>
{% endblock %}

img

接着使用WebSocket打通一条隧道,并持续更新图形。

{% extends "base.html" %}
{% block content %}
<style>
.layui-badge {
    position: absolute;
    top: 50%;
    margin-top: -9px;
    right: 15px;
    }
.title-color {
    font-style: normal;
    font-size: 30px;
    font-weight: 300;
    color: #009688;
}
.layui-span-color {
    font-size: 14px;
    position: absolute;
    right: 15px;
}
</style>
<!--------------------------------------------------------------------------------------------------------------->
<!-- 格栅,四个面板,之间相隔一定的距离-->
<div class="layui-row layui-col-space15">

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">在线用户
              <span class="layui-badge layui-bg-blue">Local User</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Count }} Users</p><br>
              <p>
              总活跃用户<span class="layui-span-color">{{ User_Count }} <i class="layui-inline layui-icon layui-icon-username"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">本机进程数
              <span class="layui-badge layui-bg-green">Process ID</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Proc }} Process</p><br>
              <p>
              总活进程数<span class="layui-span-color">{{ User_Proc }} <i class="layui-inline layui-icon layui-icon-chart-screen"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">管理主机数量
              <span class="layui-badge layui-bg-red"> Host Count</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">256 Hosting</p><br>
              <p>
              管理主机数量<span class="layui-span-color">248 <i class="layui-inline layui-icon layui-icon-user"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">当前活跃会话
              <span class="layui-badge layui-bg-orange"> Local Sesion</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Count }} Session</p><br>
              <p>
              活跃的会话<span class="layui-span-color">{{ User_Count }} <i class="layui-inline layui-icon layui-icon-user"></i></span>
              </p>
          </div>
        </div>
    </div>
</div>
<br>
<!--------------------------------------------------------------------------------------------------------------->
<!-- 系统图形统计: 动态统计系统CPU负载情况,包括CPU5,10,15等-->
<div class="layui-card" style="width:100%; height: 70%;float:left; ">
  <div class="layui-card-header">系统CPU负载</div>
        <div class="layui-card-body">
            <div id="main" style="width:100%; height: 400px;"></div>
        <br>
  </div>
</div>

<script type="text/javascript">
    var time =["","","","","","","","","","","","","","","","","","","",""];
    var cpu_load1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var cpu_load5 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var cpu_load10 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var sock = new WebSocket("ws://" + window.location.host + "/");
        sock.addEventListener("message",function (recv) {
            var js = JSON.parse(recv.data);
            time.push(js['time']);
            cpu_load1.push(parseFloat(js['load'][0]));
            cpu_load5.push(parseFloat(js['load'][1]));
            cpu_load10.push(parseFloat(js['load'][2]));
            if (time.length >=20){
                time.shift();
                cpu_load1.shift();
                cpu_load5.shift();
                cpu_load10.shift();
            }
            var main = echarts.init(document.getElementById(("main")));
            var option = {
                legend:{
                    data:['1分钟负载','5分钟负载','10分钟负载']
                },
                xAxis: {
                    type: 'category',
                    data: time
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    name: "1分钟负载",
                    type: 'line',
                    data: cpu_load1,
                    areaStyle:{}
                }, {
                name: "5分钟负载",
                type: 'line',
                data: cpu_load5,
                areaStyle:{}
                }, {
                name: "10分钟负载",
                type: 'line',
                data: cpu_load10,
                areaStyle:{}
                }]
            };
            main.setOption(option,true);
        });
        window.sock = sock;
</script>
{% endblock %}

view.py

from django.shortcuts import render
from dwebsocket.decorators import accept_websocket
import psutil,time,json

@accept_websocket
def main(request):
    if not request.is_websocket():
        User_Count = len(psutil.users())
        User_Proc = len(psutil.pids())
        return render(request, "main.html", {"User_Count": User_Count, "User_Proc": User_Proc})
    else:
        while True:
            times = time.strftime("%M:%S", time.localtime())
            data = psutil.cpu_percent(interval=None, percpu=True)
            js = {"time":times,"load":data}
            sen = json.dumps(js)
            request.websocket.send(sen)
            time.sleep(1)

img

添加内存监控图形,老样子,继续加就是了,动态图形。

{% extends "base.html" %}
{% block content %}
<style>
.layui-badge {
    position: absolute;
    top: 50%;
    margin-top: -9px;
    right: 15px;
    }
.title-color {
    font-style: normal;
    font-size: 30px;
    font-weight: 300;
    color: #009688;
}
.layui-span-color {
    font-size: 14px;
    position: absolute;
    right: 15px;
}
</style>
<!--------------------------------------------------------------------------------------------------------------->
<!-- 格栅,四个面板,之间相隔一定的距离-->
<div class="layui-row layui-col-space15">

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">在线用户
              <span class="layui-badge layui-bg-blue">Local User</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Count }} Users</p><br>
              <p>
              总活跃用户<span class="layui-span-color">{{ User_Count }} <i class="layui-inline layui-icon layui-icon-username"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">本机进程数
              <span class="layui-badge layui-bg-green">Process ID</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Proc }} Process</p><br>
              <p>
              总活进程数<span class="layui-span-color">{{ User_Proc }} <i class="layui-inline layui-icon layui-icon-chart-screen"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">管理主机数量
              <span class="layui-badge layui-bg-red"> Host Count</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">256 Hosting</p><br>
              <p>
              管理主机数量<span class="layui-span-color">248 <i class="layui-inline layui-icon layui-icon-user"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">当前活跃会话
              <span class="layui-badge layui-bg-orange"> Local Sesion</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Count }} Session</p><br>
              <p>
              活跃的会话<span class="layui-span-color">{{ User_Count }} <i class="layui-inline layui-icon layui-icon-user"></i></span>
              </p>
          </div>
        </div>
    </div>
</div>
<br>
<!--------------------------------------------------------------------------------------------------------------->
<!-- 系统图形统计: 动态统计系统CPU负载情况,包括CPU5,10,15等-->
<div class="layui-card" style="width:100%; height: 70%;float:left; ">
  <div class="layui-card-header">系统CPU负载</div>
        <div class="layui-card-body">
            <div id="cpu_load" style="width:100%; height: 400px;"></div>
        <br>
  </div>
</div>

<script type="text/javascript">
    var time =["","","","","","","","","","","","","","","","","","","",""];
    var cpu_load1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var cpu_load5 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var cpu_load10 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var sock = new WebSocket("ws://" + window.location.host + "/");
        sock.addEventListener("message",function (recv) {
            var js = JSON.parse(recv.data);
            time.push(js['time']);
            cpu_load1.push(parseFloat(js['load'][0]));
            cpu_load5.push(parseFloat(js['load'][1]));
            cpu_load10.push(parseFloat(js['load'][2]));
            if (time.length >=20){
                time.shift();
                cpu_load1.shift();
                cpu_load5.shift();
                cpu_load10.shift();
            }
            var cpu_load = echarts.init(document.getElementById(("cpu_load")));
            var option = {
                legend:{
                    data:['1分钟负载','5分钟负载','10分钟负载']
                },
                xAxis: {
                    type: 'category',
                    data: time
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    name: "1分钟负载",
                    type: 'line',
                    data: cpu_load1,
                    areaStyle:{}
                }, {
                name: "5分钟负载",
                type: 'line',
                data: cpu_load5,
                areaStyle:{}
                }, {
                name: "10分钟负载",
                type: 'line',
                data: cpu_load10,
                areaStyle:{}
                }]
            };
            cpu_load.setOption(option,true);
        });
        window.sock = sock;
</script>

<!--------------------------------------------------------------------------------------------------------------->
<!-- 同理,内存负载相同,websocket 可以重复使用-->
<div class="layui-card" style="width:100%; height: 70%;float:left; ">
  <div class="layui-card-header">系统内存统计</div>
        <div class="layui-card-body">
            <div id="mem" style="width:100%; height: 400px;"></div>
        <br>
  </div>
</div>
    
<script type="text/javascript">
    var time =["","","","","","","","","","","","","","","","","","","",""];
    var mem_load = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var sock = new WebSocket("ws://" + window.location.host + "/");
        sock.addEventListener("message",function (recv) {
            var js_mem = JSON.parse(recv.data);
            time.push(js_mem['time']);
            mem_load.push(parseFloat(js_mem['mem_used']));

            if (time.length >= 20) {
                time.shift();
                mem_load.shift();
            }
            console.log(mem_load);
            var mem = echarts.init(document.getElementById(("mem")));
            var option = {
                xAxis: {
                    type: 'category',
                    data: time
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    type: 'line',
                    data: mem_load,
                    areaStyle:{}
                }]
            };
            mem.setOption(option,true);

        });
        window.sock = sock;
</script>
{% endblock %}

view.py

from django.shortcuts import render
from dwebsocket.decorators import accept_websocket
import psutil,time,json

@accept_websocket
def main(request):
    if not request.is_websocket():
        User_Count = len(psutil.users())
        User_Proc = len(psutil.pids())
        return render(request, "main.html", {"User_Count": User_Count, "User_Proc": User_Proc})
    else:
        while True:
            times = time.strftime("%M:%S", time.localtime())
            data = psutil.cpu_percent(interval=None, percpu=True)
            mem = psutil.virtual_memory()
            mem_total = int(mem.total / 1024 / 1024)
            mem_used = int(mem.used / 1024 / 1024)
            js = {"time":times,"load":data,"mem_used":mem_used}
            sen = json.dumps(js)
            request.websocket.send(sen)
            time.sleep(1)

img

源代码案例

base.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自动化监控平台</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://www.blib.cn/cdn/layui/css/layui.css">
    <script type="text/javascript" src="https://www.blib.cn/cdn/layui/layui.js"></script>
    <script type="text/javascript" src="https://www.blib.cn/cdn/echarts.js"></script>
    <script type="text/javascript" src="https://www.blib.cn/cdn/jquery.js"></script>
</head>

{% block css %}
    <style>
        .layui-layout-admin .layui-body {
            background-color: #eee;
            padding-left: 15px;
            padding-top: 15px;
            padding-right: 15px;
        }
        .layui-layout-admin .layui-logo {
            font-size: 20px;
        }
        .layui-layout-admin .layui-footer {
            background-color: rgba(242, 242, 242, 0);
            text-align:center;
        }
    </style>
{% endblock %}

<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
  <div class="layui-header">
    <div class="layui-logo"> <i class="layui-icon layui-icon-component" style="font-size: 35px;"></i> 自动化监控平台</div>
    <!-- 头部区域(可配合layui已有的水平导航) -->
    <ul class="layui-nav layui-layout-left ">
      <li class="layui-nav-item layui-hide-xs" lay-unselect="">
        <a href="javascript:;" layadmin-event="fullscreen">
          <i class="layui-icon layui-icon-screen-full"></i>
        </a>
      </li>

      <li class="layui-nav-item"><a href="/">仪表盘</a></li>
      <li class="layui-nav-item">
            <a href="javascript:;">安全配置</a>
            <dl class="layui-nav-child">
                  <dd><a href="">邮件管理</a></dd>
                  <dd><a href="">消息管理</a></dd>
            </dl>
      </li>
    </ul>
    <!-- 右上角的基本资料配置区域-->
    <ul class="layui-nav layui-layout-right">
      <li class="layui-nav-item">
        <a href="javascript:;">
          <img src="https://www.blib.cn/cdn/head.jpg" class="layui-nav-img"> LyShark
        </a>
        <dl class="layui-nav-child">
          <dd><a href="">安全设置</a></dd>
          <dd><a href="">用户注销</a></dd>
        </dl>
      </li>
    </ul>
  </div>

  <div class="layui-side layui-bg-black">
    <div class="layui-side-scroll">
      <!-- 左侧导航区域(可配合layui已有的垂直导航) -->
      <ul class="layui-nav layui-nav-tree"  lay-filter="test">
        <li class="layui-nav-item layui-nav-itemed layui-this">
          <a class="" href="/"><i class="layui-icon layui-icon-theme"></i> 仪表盘</a>
        </li>
        <li class="layui-nav-item"><a href="/host/"><i class="layui-icon layui-icon-table"></i> 主机管理</a></li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-chart"></i> 动态监控</a></li>
      </ul>
    </div>
  </div>

  <!-- 内容主体区域 -->
  <div class="layui-body">
      {% block content %}
      {% endblock %}
  </div>
    <div class="layui-footer"> C 2018 -2020 版权所有 LyShark 保留所有权利</div>
  </div>
    <script type="text/javascript">
    var Arry  = ["/host/","/logs/"];
    for(var x=0;x<5;x++)
    {
        var log = window.location.pathname;
        if (Arry[x] == log){
            $(".layui-side-scroll li").removeClass("layui-nav-itemed")[0];
            $(".layui-side-scroll li").removeClass("layui-this")[0];
            $(".layui-side-scroll li").next().eq(x).addClass("layui-this");
            $(".layui-side-scroll li").next().eq(x).addClass("layui-nav-itemed");
        }
    }
    </script>

    <script type="text/javascript">
    layui.use('element', function(){
      var element = layui.element;
    });
    </script>
</body>
</html>

host.html

{% extends "base.html" %}
{% block content %}

<div class="layui-card" style="width:100%; height: 500px;float:left;">
  <div class="layui-card-header">系统主机组管理</div>
        <div class="layui-card-body">
            <table class="layui-hide" id="demo" lay-filter="test"></table>
        <br>
  </div>
</div>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
layui.use('table', function(){
  var table = layui.table;
  //执行一个 table 实例
  table.render({
    elem: '#demo'
    ,height: 420
    ,url: '/get_host' //数据接口
    ,title: '用户表'
    ,page: true //开启分页
      ,limit:10
    ,toolbar: 'default' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
    ,cols: [[
      {type: 'checkbox', fixed: 'left'},
      {field:'id', title:'主机ID', width:100, sort: true},
      {field:'hostname', title:'主机名称', width:120},
      {field:'hostaddr', title:'主机地址', width:120},
      {field:'hostmode', title:'主机组', width:120},
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:200}
    ]]
  });
 //监听头工具栏事件
  table.on('toolbar(test)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id)
    ,data = checkStatus.data; //获取选中的数据
    switch(obj.event){
      case 'add':
        layer.msg('添加');
      break;
      case 'update':
        if(data.length === 0){
          layer.msg('请选择一行');
        } else if(data.length > 1){
          layer.msg('只能同时编辑一个');
        } else {
          layer.alert('编辑 [id]:'+ checkStatus.data[0].id);
        }
      break;
      case 'delete':
        if(data.length === 0){
          layer.msg('请选择一行');
        } else {
          layer.msg('删除');
        }
      break;
    };
  });

  //监听行工具事件
  table.on('tool(test)', function(obj){ //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
    var data = obj.data //获得当前行数据
    ,layEvent = obj.event; //获得 lay-event 对应的值
    if(layEvent === 'detail'){
      layer.msg('查看操作');
    } else if(layEvent === 'del'){
      layer.confirm('真的删除行么', function(index){
        obj.del(); //删除对应行(tr)的DOM结构
        layer.close(index);
        //向服务端发送删除指令
      });
    } else if(layEvent === 'edit'){
      layer.msg('编辑操作');
    }
  });

  //分页
  laypage.render({
    elem: 'demo' //分页容器的id
    ,count: 100 //总页数
    ,skin: '#1E9FFF' //自定义选中色值
    //,skip: true //开启跳页
    ,jump: function(obj, first){
      if(!first){
        layer.msg('第'+ obj.curr +'页', {offset: 'b'});
      }
    }
  });
});
</script>
{% endblock %}

main.html

{% extends "base.html" %}
{% block content %}
<style>
.layui-badge {
    position: absolute;
    top: 50%;
    margin-top: -9px;
    right: 15px;
    }
.title-color {
    font-style: normal;
    font-size: 30px;
    font-weight: 300;
    color: #009688;
}
.layui-span-color {
    font-size: 14px;
    position: absolute;
    right: 15px;
}
</style>
<!--------------------------------------------------------------------------------------------------------------->
<!-- 格栅,四个面板,之间相隔一定的距离-->
<div class="layui-row layui-col-space15">

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">在线用户
              <span class="layui-badge layui-bg-blue">Local User</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Count }} Users</p><br>
              <p>
              总活跃用户<span class="layui-span-color">{{ User_Count }} <i class="layui-inline layui-icon layui-icon-username"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">本机进程数
              <span class="layui-badge layui-bg-green">Process ID</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Proc }} Process</p><br>
              <p>
              总活进程数<span class="layui-span-color">{{ User_Proc }} <i class="layui-inline layui-icon layui-icon-chart-screen"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">管理主机数量
              <span class="layui-badge layui-bg-red"> Host Count</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">256 Hosting</p><br>
              <p>
              管理主机数量<span class="layui-span-color">248 <i class="layui-inline layui-icon layui-icon-user"></i></span>
              </p>
          </div>
        </div>
    </div>

    <div class="layui-col-sm6 layui-col-md3">
        <div class="layui-card">
          <div class="layui-card-header">当前活跃会话
              <span class="layui-badge layui-bg-orange"> Local Sesion</span>
          </div>
          <div class="layui-card-body">
            <p class="title-color">{{ User_Count }} Session</p><br>
              <p>
              活跃的会话<span class="layui-span-color">{{ User_Count }} <i class="layui-inline layui-icon layui-icon-user"></i></span>
              </p>
          </div>
        </div>
    </div>
</div>
<br>
<!--------------------------------------------------------------------------------------------------------------->
<!-- 系统图形统计: 动态统计系统CPU负载情况,包括CPU5,10,15等-->
<div class="layui-card" style="width:100%; height: 70%;float:left; ">
  <div class="layui-card-header">系统CPU负载</div>
        <div class="layui-card-body">
            <div id="cpu_load" style="width:100%; height: 400px;"></div>
        <br>
  </div>
</div>

<script type="text/javascript">
    var time =["","","","","","","","","","","","","","","","","","","",""];
    var cpu_load1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var cpu_load5 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var cpu_load10 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var sock = new WebSocket("ws://" + window.location.host + "/");
        sock.addEventListener("message",function (recv) {
            var js = JSON.parse(recv.data);
            time.push(js['time']);
            cpu_load1.push(parseFloat(js['load'][0]));
            cpu_load5.push(parseFloat(js['load'][1]));
            cpu_load10.push(parseFloat(js['load'][2]));
            if (time.length >=20){
                time.shift();
                cpu_load1.shift();
                cpu_load5.shift();
                cpu_load10.shift();
            }
            var cpu_load = echarts.init(document.getElementById(("cpu_load")));
            var option = {
                legend:{
                    data:['1分钟负载','5分钟负载','10分钟负载']
                },
                xAxis: {
                    type: 'category',
                    data: time
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    name: "1分钟负载",
                    type: 'line',
                    data: cpu_load1,
                    areaStyle:{}
                }, {
                name: "5分钟负载",
                type: 'line',
                data: cpu_load5,
                areaStyle:{}
                }, {
                name: "10分钟负载",
                type: 'line',
                data: cpu_load10,
                areaStyle:{}
                }]
            };
            cpu_load.setOption(option,true);
        });
        window.sock = sock;
</script>

<!--------------------------------------------------------------------------------------------------------------->
<!-- 同理,内存负载相同,websocket 可以重复使用-->
<div class="layui-card" style="width:100%; height: 70%;float:left; ">
  <div class="layui-card-header">系统内存统计</div>
        <div class="layui-card-body">
            <div id="mem" style="width:100%; height: 400px;"></div>
        <br>
  </div>
</div>

<script type="text/javascript">
    var time =["","","","","","","","","","","","","","","","","","","",""];
    var mem_load = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var sock = new WebSocket("ws://" + window.location.host + "/");
        sock.addEventListener("message",function (recv) {
            var js_mem = JSON.parse(recv.data);
            time.push(js_mem['time']);
            mem_load.push(parseFloat(js_mem['mem_used']));
            console.log(mem_load)

            if (time.length >= 20) {
                time.shift();
                mem_load.shift();
            }
            console.log(mem_load);
            var mem = echarts.init(document.getElementById(("mem")));
            var option = {
                xAxis: {
                    type: 'category',
                    data: time
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    type: 'line',
                    data: mem_load,
                    areaStyle:{}
                }]
            };
            mem.setOption(option,true);

        });
        window.sock = sock;
</script>
{% endblock %}

urls.py

from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("",views.main),
    path("get_host/",views.get_host),
    path("host/",views.host),
]

views.py

from django.shortcuts import render,HttpResponse
from dwebsocket.decorators import accept_websocket
import psutil,time,json
from MyWeb import models


@accept_websocket
def main(request):
    if not request.is_websocket():
        User_Count = len(psutil.users())
        User_Proc = len(psutil.pids())
        return render(request, "main.html", {"User_Count": User_Count, "User_Proc": User_Proc})
    else:
        while True:
            times = time.strftime("%M:%S", time.localtime())
            data = psutil.cpu_percent(interval=None, percpu=True)
            mem = psutil.virtual_memory()
            mem_used = int(mem.used / 1024 / 1024)
            print(mem_used)
            js = {"time":times,"load":data,"mem_used":mem_used}
            sen = json.dumps(js)
            request.websocket.send(sen)
            time.sleep(1)


# 主机列表获取接口
def get_host(request):
    ret = []
    obj = models.HostDB.objects.all()
    for item in range(0,len(obj)):
        ret.append(obj.values()[item])
    data = {
        "code":0,
        "msg":"",
        "count":15,
        "total":1,
        "data": ret
    }
    return HttpResponse(json.dumps(data))

# 返回主机页面数据,或执行删除操作等
def host(request):
    return render(request,"host.html")

完整前端代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自动化监控平台</title>
    <link rel="stylesheet" href="https://www.blib.cn/cdn/layui/2.5.7/css/layui.css">
    <script type="text/javascript" src="https://www.blib.cn/cdn/layui/2.5.7/layui.js"></script>
</head>
    <style>
        .layui-layout-admin .layui-body {
            background-color: #eee;
            padding-left: 15px;
            padding-top: 15px;
            padding-right: 15px;
        }
        .layui-layout-admin .layui-logo {
            font-size: 20px;
			color: #fbfbfb;
			background-color: #1e9fff !important;
        }
        .layui-layout-admin .layui-footer {
            background-color: rgba(242, 242, 242, 0);
            text-align:center;
        }
    </style>


<body class="layui-layout-body">


<div class="layui-layout layui-layout-admin">
  <div class="layui-header">
    <div class="layui-logo"> <i style="font-size: 35px;"></i> 自动化监控平台</div>
    
	<!-- 头部区域(可配合layui已有的水平导航) -->
    <ul class="layui-nav layui-layout-left ">
      <li class="layui-nav-item layui-hide-xs" lay-unselect="">
        <a href="javascript:;" layadmin-event="fullscreen">
          <i class="layui-icon layui-icon-screen-full"></i>
        </a>
      </li>
	  
	  
	  <li class="layui-nav-item"> <a href="/"><i class="layui-icon layui-icon-theme"></i> 仪表盘</a></li>
	  
	  
	  <li class="layui-nav-item layui-hide-xs" lay-unselect="">
        <input type="text" placeholder="搜索..." autocomplete="off" class="layui-input layui-input-search"> 
      </li>
    </ul>
	
    <!-- 右上角的基本资料配置区域-->
    <ul class="layui-nav layui-layout-right">
      <li class="layui-nav-item">
        <a href="javascript:;">
          <img src="https://images.cnblogs.com/cnblogs_com/LyShark/1829666/o_200817070132o_security.png" class="layui-nav-img"> LyShark
        </a>
        <dl class="layui-nav-child">
          <dd><a href="">密码修改</a></dd>
          <dd><a href="">用户注销</a></dd>
        </dl>
      </li>
    </ul>
  </div>

  <div class="layui-side layui-bg-black">
    <div class="layui-side-scroll">
      
	  <!-- 左侧导航区域(可配合layui已有的垂直导航) -->
      <ul class="layui-nav layui-nav-tree"  lay-filter="test" >
        <li class="layui-nav-item layui-nav-itemed layui-this">
          <a class="" href="javascript:;"><i class="layui-icon layui-icon-theme"></i> 仪表盘</a>
        </li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-table"></i> 主机管理</a></li>
        <li class="layui-nav-item"><a href="javascript:;"><i class="layui-icon layui-icon-chart"></i> 动态监控</a></li>
		
		<li data-name="home" class="layui-nav-item">
              <a href="javascript:;" lay-tips="权限管理" lay-direction="2">
                <i class="layui-icon layui-icon-auz"></i>
                <cite>权限管理</cite>
              <span class="layui-nav-more"></span></a>
              <dl class="layui-nav-child">
                <dd data-name="console" class="layui-this">
                  <a lay-href="home/console.html">密码修改</a>
                </dd>
                <dd data-name="console">
                  <a lay-href="home/homepage1.html">创建用户</a>
                </dd>
                <dd data-name="console">
                  <a lay-href="home/homepage2.html">注销</a>
                </dd>
              </dl>
            </li>
      </ul>
    </div>
  </div>


  <!-- 内容主体区域 -->
  <div class="layui-body">
      {% block content %}
      {% endblock %}
  </div>
  
  
  <!--页脚部分-->
  <div class="layui-footer"> C 2018 -2021 自动化运维平台 By:LyShark</div></div>
  <!--
    <script type="text/javascript">
    var Arry  = ["/host/","/logs/"];
    for(var x=0;x<5;x++)
    {
        var log = window.location.pathname;
        if (Arry[x] == log){
            $(".layui-side-scroll li").removeClass("layui-nav-itemed")[0];
            $(".layui-side-scroll li").removeClass("layui-this")[0];
            $(".layui-side-scroll li").next().eq(x).addClass("layui-this");
            $(".layui-side-scroll li").next().eq(x).addClass("layui-nav-itemed");
        }
    }
    </script>
	-->
	
    <script type="text/javascript">
    layui.use('element', function(){
      var element = layui.element;
    });
    </script>
</body>
</html>