admin 管理员组

文章数量: 1184232

使用Python打造实时资源监控仪表盘(psutil+FastAPI)

一、为什么要学习系统监控?

在软件开发中,系统资源监控是每个开发者都需要掌握的重要技能。无论是排查性能瓶颈、优化程序效率,还是确保服务稳定性,实时掌握CPU、内存、磁盘等关键指标都至关重要。

本教程将带您从零开始,使用Python生态中的两个强力工具:

  • psutil :跨平台系统信息监控库
  • FastAPI :现代高性能Web框架

最终实现一个具备以下功能的实时监控仪表盘:
✅ 实时CPU使用率监控
✅ 内存使用量可视化
✅ 历史数据趋势图表
✅ 动态刷新的Web界面


二、环境准备与工具安装

2.1 安装必要库

pip install psutil fastapi uvicorn jinja2 python-multipart

2.2 创建项目结构

monitor_dashboard/
├── main.py         # FastAPI主程序
├── templates/      # 前端模板
│   └── index.html
└── static/         # 静态资源
    ├── style.css
    └── chart.js

三、psutil核心功能解析

3.1 基本使用示例

import psutil
# 获取CPU信息print(f"CPU核心数: {
     
     psutil.cpu_count(logical=False)}")print(f"当前CPU使用率: {
     
     psutil.cpu_percent(interval=1)}%")# 获取内存信息
mem = psutil.virtual_memory()print(f"内存总量: {
     
     mem.total /1024**3:.2f}GB")print(f"已用内存: {
     
     mem.used /1024**3:.2f}GB")# 获取磁盘信息
disk = psutil.disk_usage('/')print(f"磁盘总空间: {
     
     disk.total /1024**3:.2f}GB")

3.2 关键API说明

功能 API 返回示例
CPU使用率 cpu_percent(interval=1) 15.6
内存信息 virtual_memory() svmem(total=17064538112, …)
磁盘使用 disk_usage(‘/’) sdiskusage(total=256GB, …)
网络流量 net_io_counters() snetio(bytes_sent=1024MB…)

四、构建监控后端服务

4.1 FastAPI基础框架

from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")@app.get("/")asyncdefdashboard(request: Request):return templates.TemplateResponse("index.html"

本文标签: 使用 信息 解析