还未完善,后续会更新
创建Django项目
创建app
python manage.py startapp host
创建成功后会出现以下文件
设置时区语言
数据库表生成
$ python manage.py migrate # 将迁移脚本的内容写入数据库并创建数据库表
$ python manage.py createsuperuser # 创建后台登录的超级用户
启动开发服务器
python manage.py runserver
浏览器访问,检测是否成功?
访问网址: http://127.0.0.1:8000
http://127.0.0.1:8000/admin
git管理项目
创建README.md并写入信息
创建 requrements.txt
pip freeze > requrements.txt
创建.gitignore
配置
apps函数(新建)
# sysinfo/host/apps.py(新建)
from django.apps import AppConfig
class HostConfig(AppConfig):
name = 'host'
urls函数(新建)
# sysinfo/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'),
]
视图函数
# sysinfo/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):
users = psutil.users()
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())
在sysinfo/template/host新建html文件
sysinfo/settings
# sysinfo/settings
STATICFILES_DIRS = [
BASE_DIR / "static",
]
编写html文件
base.html
# sysinfo/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>
cpu.html
# sysinfo/templates/host/cpu.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
disk.html
# sysinfo/templates/host/disk.html
{% include 'host/base.html' %}
{% block title %}
磁盘信息
{% endblock %}
{% block content %}
<h3>disk的内容</h3>
{% endblock %}
index.html
# sysinfo/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 %}
memory.html
# sysinfo/templates/host/memory.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
network.html
# sysinfo/templates/host/network.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
process.html
# sysinfo/templates/host/process.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
导入static文件夹(将文件夹放在与host文件夹同一级目录)
https://gitee.com/half-summer/sysinfo
测试
访问http://127.0.0.1:8000/
用户详情
user.html
# sysinfo/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 %}
sysinfo/host/templatetags(新建)
# sysinfo/host/templatetags/timefilter.py(新建)
"""
自定义过滤器实现的方法:
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/
点击用户一栏可以查看用户信息详情
cpu信息
cpu.html
# sysinfo/templates/host/cpu.html
{% extends 'host/base.html' %}
{% load timefilter %}
{% block title %} cpu信息 {% endblock %}
{% block content %}
<div class="page-header">
<a {% if not chart %}id="display"{% endif %} href="/cpu/">CPU 信息</a>
<a {% if chart == 'line' %}id="display"{% endif %} href="/cpu/">CPU
折线图</a>
<a {% if chart == 'pie' %}id="display"{% endif %} href="/cpu/">CPU 饼图</a>
</div>
<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>
{% endblock %}
视图函数
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):
users = psutil.users()
return render(request, 'host/user.html', locals())
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())
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())
自定义信息
# sysinfo/host/templatetags/timefilter.py
"""
自定义过滤器实现的方法:
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)
# 新添加的部分
@register.filter(name='cpu_val_fmt')
def cpu_val_fmt(value):
return round(value/1000, 2)
测试
访问http://127.0.0.1:8000/cpu/
cpu折线图和饼图
models.py
# sysinfo/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占用百分比")
urls.py
# sysinfo/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('cpu/<str:chart>/', cpu, name='cpu'),
path('memory/', memory, name='memory'),
path('disk/', disk, name='disk'),
path('network/', network, name='network'),
path('process/', process, name='process'),
]
views.py
# sysinfo/host/views.py
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())
base.html
# sysinfo/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>
<script src="https://lib.baomitu.com/echarts/5.0.2/echarts.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>
执行以下命令
python manage.py makemigrations
python manage.py migrate
此时会出现host/migrations/0001_initial.py这个文件
templates/host/cpu-header.html(新建)
# templates/host/cpu-header.html
<div class="page-header">
<a {% if not chart %}id="display"{% endif %} href="/cpu/">CPU 信息</a>
<a {% if chart == 'line' %}id="display"{% endif %} href="/cpu/line/">CPU
折线图</a>
<a {% if chart == 'pie' %}id="display"{% endif %} href="/cpu/pie/">CPU 饼图</a>
</div>
templates/host/cpu-line.html(新建)
# templates/host/cpu-line.html
{% extends 'host/base.html' %}
{% load timefilter %}
{% block title %} cpu信息 {% endblock %}
{% block content %}
{% include 'host/cpu-header.html' %}
<div>
<div id="main" style="width: 80%;height:400px;"></div>
</div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
{% endblock %}
templates/host/cpu-pie.html(新建)
# templates/host/cpu-pie.html
{% extends 'host/base.html' %}
{% load timefilter %}
{% block title %} cpu信息 {% endblock %}
{% block content %}
{% include 'host/cpu-header.html' %}
<div>
<div id="main" style="width: 80%;height:400px;"></div>
</div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
option = {
tooltip: {
trigger: 'item'
},
legend: {
top: '5%',
left: 'center'
},
series: [
{
name: 'CPU占用百分比分类',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '40',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{value: {{ cpu_time_percent.user }}, name: '用户'},
{value: {{ cpu_time_percent.system }}, name: '系统'},
{value: {{ cpu_time_percent.idle }}, name: '空闲'},
]
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
{% endblock %}
测试
访问http://127.0.0.1:8000/cpu/
此时可以点击cpu折线图和cpu饼图,看到相关信息
Celery定时任务和异步任务
Celery 是一个简单、灵活且可靠的,处理大量消息的分布式系统。大白话理解处理异步任务和定时任务
的工具。
工作原理如下图:
执行下列命令,安装插件
pip install celery -i https://pypi.douban.com/simple
pip install django-celery-beat -i https://pypi.douban.com/simple
pip install django-celery-results -i https://pypi.douban.com/simple
sysinfo/host/tasks.py(新建)
sysinfo/sysinfo/celery.py(新建)
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# 设置django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sysinfo.settings')
app = Celery('sysinfo')
# 使用CELERY_ 作为前缀,在settings中写配置
app.config_from_object('django.conf:settings', namespace='CELERY')
# 发现任务文件每个app下的task.py
app.autodiscover_tasks()
sysinfo/init.py
from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app
__all__ = ['celery_app']
sysinfo/host/settings.py
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&@3orc)0&81b3vni!ks^zy3v+i0^*qw(5!pz+tlme02prirq%!'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_celery_beat',
'host',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'sysinfo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'sysinfo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'
# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
# USE_TZ = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATICFILES_DIRS = [
BASE_DIR / "static",
]
STATIC_URL = '/static/'
# celery configure
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' # Broker配置,使用Redis作为消息中间件
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/1' # BACKEND配置,这里使用redis
CELERY_RESULT_SERIALIZER = 'json' # 结果序列化方案
安装Redis
详细步骤见网址
https://www.redis.com.cn/redis-installation.html
安装后会自动开启
/sysinfo/venv/worker.sh
Celery -A sysinfo worker -l info -P eventlet
执行命令
Celery -A sysinfo worker -l info -P eventlet
此时会出现错误
安装eventlet
pip install eventlet -i https://pypi.douban.com/simple
此时再次执行命令就成功了
sysinfo/host/tasks.py(新建)
import psutil
from celery import shared_task
from host.models import UserCpuPercent
@shared_task()
def scan_cpu_info():
percent = UserCpuPercent( user_percent=psutil.cpu_times_percent().user)
percent.save()
数据库变更
python manage.py makemigrations
python manage.py migrate
测试
访问http://127.0.0.1:8000/admin/
添加定时任务
此时定时任务并不会执行
sysinfo/venv/start_celery.sh(新建)
celery -A sysinfo beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler
再次执行就可以了
cpu折线图
视图函数
# sysinfo/host/views.py
from datetime import datetime
from django.shortcuts import render
import psutil
import os, platform
# Create your views here.
from host.models import UserCpuPercent
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':
datas = UserCpuPercent.objects.order_by('-id')[:30]
print(datas)
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())
templates/host/cpu-line.html
{% extends 'host/base.html' %}
{% load timefilter %}
{% block title %} cpu信息 {% endblock %}
{% block content %}
{% include 'host/cpu-header.html' %}
<div>
<div id="main" style="width: 80%;height:400px;"></div>
</div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
{#首先,声明两个 javascript 的数组#}
var series_data = [];
var xAxis_data = [];
{#使用循环,依次将数据库需要展示的数据添加到刚才声明的数组中#}
{% for data in datas %}
{#series_data.push({{ data.user_percent }})#}
{#xAxis_data.push({{ data.create_time }})#}
series_data.push({{ data.user_percent }})
{#注意这里的双引号#}
xAxis_data.push("{{ data.create_time}}")
{% endfor %}
option = {
xAxis: {
type: 'category',
data: xAxis_data
},
yAxis: {
type: 'value'
},
series: [{
data: series_data,
type: 'line',
smooth: true
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
{% endblock %}
templates/host/cpu-pie.html
{% extends 'host/base.html' %}
{% load timefilter %}
{% block title %} cpu信息 {% endblock %}
{% block content %}
{% include 'host/cpu-header.html' %}
<div>
<div id="main" style="width: 80%;height:400px;"></div>
</div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
option = {
tooltip: {
trigger: 'item'
},
legend: {
top: '5%',
left: 'center'
},
series: [
{
name: 'CPU占用百分比分类',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '40',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{value: {{ cpu_time_percent.user }}, name: '用户'},
{value: {{ cpu_time_percent.system }}, name: '系统'},
{value: {{ cpu_time_percent.idle }}, name: '空闲'},
]
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
{% endblock %}
测试
访问http://127.0.0.1:8000/cpu
点击cpu折线图可以查看信息