文章目录
本文参照https://github.com/hypersport/sysinfo
代码参考https://gitee.com/half-summer/sysinfo.git
1、搭建项目环境
-
新建project->Django项目,选择虚拟环境:是个隔离的环境,与python无关
-
创建app
#Terminal命令行执行
python manage.py startapp login
- 设置时区和语言
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'host',
]
# 编辑文件 loginRegister/settings.py
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'
# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'
- 数据库表生成
#Terminal命令行执行
python manage.py makemigrations
python manage.py migrate # 将迁移脚本的内容写入数据库并创建数据库表
python manage.py createsuperuser # 创建后台登录的超级用户和密码
- 启动开发服务器
方法1:命令启动
#Terminal命令行执行
python manage.py runserver
- git
安装.ignore插件
git init
git add *
(venv) E:\wode wendang ya\chaoyouxiu\python_kecheng\day10练习\sysinfo>pip freeze
asgiref==3.3.1
Django==3.1.7
psutil==5.8.0
pytz==2021.1
sqlparse==0.4.1
(venv) E:\wode wendang ya\chaoyouxiu\python_kecheng\day10练习\sysinfo>pip freeze > requirements.txt
2.urls路由
#sysinfo/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('host.urls')),
]
```python
#新建子urls:host/urls.py
from django.contrib import admin
from django.urls import path, include
from .views import *
urlpatterns = [
path('', index, name='index'),
path('user/', user, name='user'),
path('cpu/', cpu, name='cpu'),
path('memory/', memory, name='memory'),
path('disk/', disk, name='disk'),
path('network/', network, name='network'),
path('process/', process, name='process'),
]
3.视图函数框架搭建
psutil模块:https://www.cnblogs.com/saneri/p/7528283.html
1)创建html
2)编写html模板base.html
#templates/host/base.html
<!DOCTYPE html>
<html {% block html_attribs %}{% endblock html_attribs %}>
<head>
{% block head %}
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %} {% endblock title %}</title>
<link rel="stylesheet" type="text/css" href="/static/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/static/css/my-style.css">
<script src="/static/js/jquery-3.1.1.min.js"></script>
{% endblock head %}
</head>
<body>
<div class="sysinfo">
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Sys Info</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">系统</a></li>
<li><a href="/cpu/">CPU</a></li>
<li><a href="/memory/">内存</a></li>
<li><a href="/disk/">硬盘</a></li>
<li><a href="/network/">网络</a></li>
<li><a href="/process/">进程</a></li>
<li><a href="/user/">用户</a></li>
</ul>
</div>
</div>
</div>
<div class="container">
{% block content %}{% endblock %}
</div>
</div>
</body>
</html>
3)编写首页index.html和视图函数
#templates/host/index.html
{% extends 'host/base.html' %}
{% block title %}Sys Info{% endblock %}
{% block content %}
<div class="page-header">
<h1>系统信息</h1>
</div>
<div>
<table class="table table-bordered">
<tr>
<td>主机名</td>
<td>{{ sys_name }}</td>
</tr>
<tr>
<td>内核名称</td>
<td>{{ kernel_name }}</td>
</tr>
<tr>
<td>发行版本号</td>
<td>{{ kernel_no }}</td>
</tr>
<tr>
<td>内核版本</td>
<td>{{ kernel_version }}</td>
</tr>
<tr>
<td>系统架构</td>
<td>{{ sys_framework }}</td>
</tr>
<tr>
<td>现在时间</td>
<td>{{ now_time }}</td>
</tr>
<tr>
<td>开机时间</td>
<td>{{ boot_time }}</td>
</tr>
<tr>
<td>运行时间</td>
<td>{{ up_time }}</td>
</tr>
</table>
</div>
{% endblock %}
视图函数
#sysinfo/settings.py
STATICFILES_DIRS = [
BASE_DIR / "static",
]
STATIC_URL = '/static/'
#Terminal命令行执行
pip install psutil
#host/views.py
from datetime import datetime
from django.shortcuts import render
import psutil
import os, platform
# Create your views here.
def index(request):
"""
sys_name
kernel_name
kernel_no
kernel_version
sys_framework
now_time
boot_time
up_time
"""
try:
info = os.uname()
except Exception as e:
info = platform.uname()
sys_name = info.node
kernel_name = info.system
kernel_no = info.release
kernel_version = info.version
sys_framework = info.machine
boot_time = datetime.fromtimestamp(psutil.boot_time())
now_time = datetime.now()
print(boot_time, now_time)
up_time = now_time - boot_time
return render(request, 'host/index.html', locals())
def user(request):
pass
return render(request, 'host/user.html', locals())
def cpu(request):
pass
return render(request, 'host/cpu.html', locals())
def memory(request):
pass
return render(request, 'host/memory.html', locals())
def disk(request):
pass
return render(request, 'host/disk.html', locals())
def network(request):
pass
return render(request, 'host/network.html', locals())
def process(request):
pass
return render(request, 'host/process.html', locals())
访问http://127.0.0.1:8000/
4)编写user及其视图
- 视图函数
- 前端user
#templates/host/user.html
{% extends 'host/base.html' %}<!-- 继承基本模板 -->
{% load timefilter %}<!-- 加载自定义的过滤器 -->
{% block title %} 用户信息 {% endblock %}
{% block content %}
<div class="page-header">
<h1>登录用户</h1>
</div>
<div>
<table class="table table-bordered">
<tr>
<td>用户名</td>
<td>登录主机</td>
<td>终端</td>
<td>登录时间</td>
</tr>
{% for user in users %}
<tr>
<td>{{ user.name }}</td>
<td>{{ user.terminal }}</td>
<td>{{ user.host }}</td>
<td>{{ user.started | timefmt }}</td><!-- 使用过滤器 -->
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
- 注册和使用自定义过滤器
#host下创建templatetags包(名字必须是templatetags)
"""
自定义过滤器实现的方法:
https://docs.djangoproject.com/zh-hans/3.1/howto/custom-template-tags/
"""
from django import template
from datetime import datetime
register = template.Library()
@register.filter(name='timefmt')
def timefmt(value):
"""将时间戳转换成datetime类型的时间"""
return datetime.fromtimestamp(value)
- 测试:网页访问http://127.0.0.1:8000/user/
注意添加了文件,要重启python manage.py runserver,才能生效
5)编写CPU及其视图
#host/views.py
def cpu(request):
logical_core_num = psutil.cpu_count() #
physical_core_num = psutil.cpu_count(logical=False)
try:
load_avg = os.getloadavg()
except Exception as e:
load_avg = ['', '', '']
cpu_time_percent = psutil.cpu_times_percent()
else_percent = 0.0
for i in range(5):
else_percent += cpu_time_percent[i]
try:
cpu_freq = psutil.cpu_freq()
except AttributeError:
cpu_freq = None
return render(request, 'host/cpu.html', locals())
4.功能完善(CPU基于echarts的扇形图展示)
1)路由
2)视图
from datetime import datetime
from django.shortcuts import render
import psutil
import os, platform
# Create your views here.
def index(request):
try:
info = os.uname()
except Exception as e:
info = platform.uname()
sys_name = info.node
kernel_name = info.system
kernel_no = info.release
kernel_version = info.version
sys_framework = info.machine
boot_time = datetime.fromtimestamp(psutil.boot_time())
now_time = datetime.now()
print(boot_time, now_time)
up_time = now_time - boot_time
return render(request, 'host/index.html', locals())
def user(request):
users = psutil.users()
return render(request, 'host/user.html', locals())
def cpu(request, chart=None):
logical_core_num = psutil.cpu_count() #
physical_core_num = psutil.cpu_count(logical=False)
try:
load_avg = os.getloadavg()
except Exception as e:
load_avg = ['', '', '']
cpu_time_percent = psutil.cpu_times_percent()
else_percent = 0.0
for i in range(3, 5):
else_percent += cpu_time_percent[i]
try:
cpu_freq = psutil.cpu_freq()
except AttributeError:
cpu_freq = None
if chart == 'line':
return render(request, 'host/cpu-line.html', locals())
elif chart == 'pie':
return render(request, 'host/cpu-pie.html', locals())
return render(request, 'host/cpu.html', locals())
def memory(request):
pass
return render(request, 'host/memory.html', locals())
def disk(request):
pass
return render(request, 'host/disk.html', locals())
def network(request):
pass
return render(request, 'host/network.html', locals())
def process(request):
pass
return render(request, 'host/process.html', locals())
3)前端
{% extends 'host/base.html' %}
{% load timefilter %}
{% block title %} cpu信息 {% endblock %}
{% block content %}
{% include 'host/cpu-header.html' %}
<div>
<div id="cpu_info">
<table class="table table-bordered">
<tr>
<td>物理 CPU 核心数</td>
<td>{{ physical_core_num }}</td>
</tr>
<tr>
<td>逻辑 CPU 核心数</td>
<td>{{ logical_core_num }}</td>
</tr>
<tr>
<td>最近 1 分钟平均负载</td>
<td>{{ load_avg.0 }}</td>
</tr>
<tr>
<td>最近 5 分钟平均负载</td>
<td>{{ load_avg.1 }}</td>
</tr>
<tr>
<td>最近 15 分钟平均负载</td>
<td>{{ load_avg.2 }}</td>
</tr>
<tr>
<td>用户</td>
<td>{{ cpu_time_percent.user }} %</td>
</tr>
<tr>
<td>系统</td>
<td>{{ cpu_time_percent.system }} %</td>
</tr>
<tr>
<td>空闲</td>
<td>{{ cpu_time_percent.idle }} %</td>
</tr>
{% if cpu_time_percent.nice %}
<tr>
<td>nice</td>
<td>{{ cpu_time_percent.nice }} %</td>
</tr>
{% endif %}
{% if cpu_time_percent.iowait %}
<tr>
<td>iowait</td>
<td>{{ cpu_time_percent.iowait }} %</td>
</tr>
{% endif %}
{% if else_percent %}
<tr>
<td>其他</td>
<td>{{ else_percent }} %</td>
</tr>
{% endif %}
{% if cpu_freq %}
<tr>
<td>正在运行频率</td>
<td>{{ cpu_freq.current | cpu_val_fmt }} GHz</td>
</tr>
<tr>
<td>最低运行频率</td>
<td>{{ cpu_freq.min | cpu_val_fmt }} GHz</td>
</tr>
<tr>
<td>最高运行频率</td>
<td>{{ cpu_freq.max | cpu_val_fmt }} GHz</td>
</tr>
{% endif %}
</table>
</div>
</div>
{% endblock %}
#host/models.py,编写数据库
from django.db import models
# Create your models here.
# 定时任务定期扫描并存储。
class UserCpuPercent(models.Model):
create_time = models.DateTimeField(auto_now_add=True, verbose_name="扫描时间")
user_percent = models.FloatField(verbose_name="用户CPU占用百分比")
#执行迁移脚本
python manage.py makemigrations
python manage.py migrate
5.定时任务:celery
装包
新建celery
init写入
settings写入
安装redis