7-3 数据可视化psutil+pygal+flask
前置课程8-1Flask框架入门。
本节性质:课外拓展。
引题
可视化的重要性:对于网工专业来说,并不要求会软件专业的前端图表。但上节课已经拿到数据了,还差一步就可以"表现"出来了。
我见过一些做软件后端的程序员,他们会写复杂的逻辑,但在面试时面对人事和老板,无法很好表达出自己的实力。
所以我建议学一点前端,可以更好表现自己的作品。而且,Python里的一些库会帮助我们生成前端图表,而不需要掌握前端知识,只需要喂数据。
上一节课得到的设备推送数据
cpuInfos {
cpuInfo {
entIndex: 17891329
interval: 8
ovloadThreadhold: 90
position: "17"
systemCpuUsage: 1
unovloadThreshold: 75
}
}
cpuInfos: 父级容器。
cpuInfo: 子级容器,单个 CPU 的信息。
entIndex: 17891329: 实体索引唯一标识该CPU实例的索引值。
interval: 8: 采样间隔
ovloadThreadhold: 90: 过载阈值 (Overload Threshold)。当 CPU 使用率超过这个值时,设备可能会认为该 CPU 处于过载状态,并可能触发告警或采取相应的保护措施。
position: "17": 位置标识,标识 CPU 在设备中的物理或逻辑位置,可能代表第 17 个 CPU 核心或逻辑处理器。
systemCpuUsage: 1: 系统CPU使用率(System CPU Usage)。1%占用率。
unovloadThreshold: 75: 解除过载阈值 (Unload Threshold)。这是一个百分比数值,表示当 CPU 使用率从过载状态回落到这个值以下时,设备可能会认为过载状态解除。这里的 75 表示当 CPU 使用率低于 75% 时,过载状态被认为已经解除。
YANG建模语言介绍和解析
YANG: (Yet Another Next Generation) 下一代数据建模语言,专门用于网络设备的配置、状态数据、操作和通知的描述。最初是为NetConf协议设计的,其它协议如RESTConf也可以使用。
概念包含:模块、数据节点(子节点、兄弟节点、列表、容器)、数据类型(int32, string, binary, leafref)、约束、操作(通过rpc执行测定动作)、通知、扩展、条件控制 应用场景有:定义 NETCONF 和 RESTCONF API。自动化网络配置。监控网络状态。开发网络管理应用。SDN (Software-Defined Networking)。
用之前学过的概念做类比,在配置上,很像Linux上的配置文件,在数据传输上,很像XML/JSON这种脱离平台的格式。
YANG与python内置结构互转:略。虽然是网工设备专用,但在整个计算机领域还是xml/json更加通用和可读性好。目前的章节实验也仅用YANG来传输数据。
psutil库
psutil可以获取系统性能数据
import psutil
# CPU 使用率
print(f"CPU 使用率: {psutil.cpu_percent(interval=0.5)}%")
# 内存使用率
print(f"内存使用率: {psutil.virtual_memory().percent}%")
# 磁盘使用率 (根分区)
print(f"磁盘使用率 (/): {psutil.disk_usage('/').percent}%")
# 网络发送字节数
print(f"网络发送 (总): {psutil.net_io_counters().bytes_sent}")
# 当前进程名称
print(f"当前进程名称: {psutil.Process().name()}")
pygal库
pygal是一个简易的图表绘制库(比起matplotlib这种更为专业重型的库)。
pygal 官方网站
# 折线图
import pygal
line_chart = pygal.Line()
line_chart.title = 'Browser usage evolution (in %)'
line_chart.x_labels = ['2012', '2013', '2014', '2015', '2016', '2017']
line_chart.add('Firefox', [12, 19, 15, 20, 23, 25])
line_chart.add('Chrome', [30, 35, 40, 45, 50, 55])
line_chart.add('IE', [52, 39, 31, 15, 10, 4])
line_chart.render_to_file('line_chart.svg')
绘制实时图表小项目
前置课程8-1HTTP协议与Flask框架入门
准备服务器返回数据
安装三方库
pip install flask psutil pygal -i https://mirrors.aliyun.com/pypi/simple/
项目结构
-- pythonProject
-- templates
-- index.html
-- app.py
app.py
import psutil
import time
import pygal
from flask import Flask, render_template
from collections import deque
app = Flask(__name__)
# 存储 CPU 使用率数据的队列
cpu_history = deque(maxlen=30)
time_history = deque(maxlen=30)
start_time = time.time()
def get_cpu_chart():
cpu_percent = psutil.cpu_percent(interval=0.5)
current_time = time.time() - start_time
cpu_history.append(cpu_percent)
time_history.append(current_time)
line_chart = pygal.Line(x_label_rotation=20)
line_chart.title = 'Real-time CPU Usage (%)'
line_chart.x_labels = [f'{t:.1f}s' for t in time_history]
line_chart.add('CPU Usage', list(cpu_history))
return line_chart.render_data_uri()
@app.route('/')
def index():
chart_data = get_cpu_chart()
return render_template('index.html', chart_data=chart_data)
@app.route('/update_chart')
def update_chart():
chart_data = get_cpu_chart()
return chart_data
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Real-time CPU Monitor</title>
<script>
function updateChart() {
fetch('/update_chart')
.then(response => response.text())
.then(data => {
document.getElementById('cpu-chart').src = data;
});
}
setInterval(updateChart, 1000); // 每 1 秒更新图表
</script>
</head>
<body>
<h1>Real-time CPU Usage</h1>
<img id="cpu-chart" src="{{ chart_data }}" alt="CPU Usage Chart">
</body>
</html>

运行
运行 app.py
浏览器访问 127.0.0.1:8080/ (实际IP和端口号与app.py中的值保持一致。)
得到目前章节为止最直观的一个结果。
![7 3]()
15 五月 2025