通过django结合hcharts实现数据可视化


         我们都知道现在到处都是轮子,但是还想自己去造一个属于自己的轮子,所以自己在学习django的同时也尝试模仿着别人造轮子。django怎么样就不说了,让别人度娘去吧;

通过django结合hcharts动态展现内存使用率,实现单机内存监控效果,因为度娘里的echarts文档相对难看懂,觉得hcharts实现比较简单。

 

本文基于Centos7下虚拟环境安装:Python3.5.2实现;

Ip地址:10.0.10.250

运行环境:

 
  1. (py35env) [root@jupyter memory]# pip list 
  2. appdirs (1.4.3) 
  3. decorator (4.0.11) 
  4. Django (1.11.1) 
  5. ipython (6.0.0) 
  6. ipython-genutils (0.2.0) 
  7. jedi (0.10.2) 
  8. packaging (16.8) 
  9. pexpect (4.2.1) 
  10. pickleshare (0.7.4) 
  11. pip (9.0.1) 
  12. prompt-toolkit (1.0.14) 
  13. ptyprocess (0.5.1) 
  14. Pygments (2.2.0) 
  15. PyMySQL (0.7.11)    #python3使用mysql的工具包变成了这个名字; 
  16. pyparsing (2.2.0) 
  17. pytz (2017.2) 
  18. requests (2.14.2)    
  19. setuptools (35.0.2)     #安装PyMySQL前先yum install setuptool -y 
  20. simplegeneric (0.8.1) 
  21. six (1.10.0) 
  22. traitlets (4.3.2) 
  23. wcwidth (0.1.7) 
  24. wheel (0.29.0) 
 

其实很多实验之所以会失败大部分都是软件的版本和兼容性不同导致,本文是参考了51reboot的内存可视化演变而来,只是我使用了自己最近学习的django来实现前端展现。

1、创建一个project:

 
  1. django-admin startproject memory 

2、进入memory目录下并创建一个app:

 
  1. cd memory && django-admin startapp blog 

3、创建两个目录,static和templates,一个存放静态页面和静态文件如js、css;

 
  1. mkdir static templates 

查看目录结构:

 
  1. (py35env) [root@jupyter ~]# tree -d memory/ -L 1 
  2. memory/ 
  3. ├── blog 
  4. ├── memory 
  5. ├── static 
  6. └── templates 
 

使用这个图形,并把html代码里的4个js文件下载到static/js下:https://www.hcharts.cn/demo/highstock/spline

jquery-1.8.3.min.js、highstock.js、exporting.js、highcharts-zh_CN.js

 

4、接下来配置一下memory/setting.py:

 
  1. 28 ALLOWED_HOSTS = ['*']            #改成'*'                                                 
  2.  
  3. 55 TEMPLATES = [                                                                     
  4. 56     {                                                                             
  5. 57         'BACKEND': 'django.template.backends.django.DjangoTemplates',             
  6. 58         'DIRS': [                                                                 
  7. 59             os.path.join(BASE_DIR, 'templates'),        #加入这一行,html文件的目录                          
  8. 60         ],                                                                        
  9. 61         'APP_DIRS': True,                                                         
  10. 62         'OPTIONS': {                                                              
  11. 63             'context_processors': [                                               
  12. 64                 'django.template.context_processors.debug',                       
  13. 65                 'django.template.context_processors.request',                     
  14. 66                 'django.contrib.auth.context_processors.auth',                    
  15. 67                 'django.contrib.messages.context_processors.messages',            
  16. 68             ],                                                                    
  17. 69         },                                                                        
  18. 70     },                                                                            
  19. 71 ] 
 

最后面添加,静态js和CSS文件的存放目录:

 
  1. 124 STATICFILES_DIRS = (                                                                                                                                     
  2. 125     os.path.join(BASE_DIR, 'static'),                                             
  3. 126 )  

5、配置blog/views.py文件:

  1. #!/usr/bin/env python3                                                               
  2. # -*- coding:UTF-8 -*-                                                               
  3. from django.shortcuts import render                                                  
  4. from django.http import HttpResponse                                                 
  5. import pymysql as mysql                                                              
  6. import json                                                                          
  7. import requests                                                                      
  8.                                                                                      
  9. # Create your views here.                                                            
  10. tmp_time = 0                                                                         
  11. con = mysql.connect(user='dba',passwd='123456',host='localhost',db='memory')         
  12. con.autocommit(True)                                                                 
  13. cur = con.cursor()                                                                   
  14.                                                                                      
  15. def index(request):                                                                  
  16.     return render(request, 'demo.html')                                              
  17.                                                                                      
  18. def data(request):                                                                                                                                            
  19.     global tmp_time                                                                  
  20.     if tmp_time>0:                                                                   
  21.         sql = 'select * from memory where time>%s' %(tmp_time/1000)                  
  22.     else:                                                                            
  23.         sql = 'select * from memory'                                                 
  24.     cur.execute(sql)                                                                 
  25.     arr = []                                                                         
  26.     for i in cur.fetchall():                                                         
  27.         arr.append([i[1]*1000,i[0]])                                                 
  28.     if len(arr)>0:                                                                   
  29.         tmp_time = arr[-1][0]                                                        
  30.     return HttpResponse(json.dumps(arr))  

6、配置url.py文件:

  1. 16 from django.conf.urls import url                                                  
  2.  17 from django.contrib import admin                                                  
  3.  18 from blog import views as blog_views          #引入blog里的views文件,并定义一个别名;                                    
  4.  19                                                                                   
  5.  20 urlpatterns = [                                                                   
  6.  21     url(r'^admin/', admin.site.urls),                                             
  7.  22     url(r'^$', blog_views.index),      #以下两行为加入内容                                           
  8.  23     url(r'^data/',blog_views.data),                                                                                                                          
  9.  24 ]         
 

7、 接下来创建一个静态html文件,也就是views.py里定义的demo.html文件:

(py35env) [root@jupyter memory]# vim templates/demo.html 
 
 
  1. {% load static %}       #引入static目录下的静态文件要先加入此行 
  2. <!DOCTYPE html> 
  3. <html lang="en"> 
  4. <head> 
  5.     <meta charset="UTF-8"> 
  6.     <title>内存监控信息</title> 
  7.     <script src="{% static 'js/jquery-1.8.3.min.js' %}"></script> 
  8.     <script src="{% static 'js/highstock.js' %}"></script> 
  9.     <script src="{% static 'js/exporting.js' %}"></script> 
  10.     <script src="{% static 'js/highcharts-zh_CN.js' %}"></script> 
  11. </head> 
  12. <body> 
  13.     <div id="container" style="min-width:400px; height:400px"></div> 
  14.     <script> 
  15.             $(function () { 
  16.             $.getJSON('/data', function (data) { 
  17.                 // Create the chart 
  18.                 $('#container').highcharts('StockChart', { 
  19.                     chart:{ 
  20.                         events:{ 
  21.                             load:function(){ 
  22.                                 var series = this.series[0] 
  23.                                 setInterval(function(){ 
  24.                                 $.getJSON('/data',function(res){ 
  25.                                     $.each(res,function(i,v) { 
  26.                                         series.addPoint(v) 
  27.                                     }) 
  28.                                 }) 
  29.                                 },3000) 
  30.                             } 
  31.                         } 
  32.                     }, 
  33.                     rangeSelector: { 
  34.                         selected: 1 
  35.                     }, 
  36.                     title: { 
  37.                         text: '内存使用率-单位M' 
  38.                     }, 
  39.                     series: [{ 
  40.                         name: '内存使用率', 
  41.                         data: data, 
  42.                         type: 'spline', 
  43.                         tooltip: { 
  44.                             valueDecimals: 2 
  45.                         } 
  46.                     }] 
  47.                 }); 
  48.             }); 
  49.         }); 
  50.     </script> 
  51. </body> 
  52. </html> 
 

其实仔细看跟hcharts上面的实例差不多,只是加入了几行代码实现动态刷新;

 
  1. chart:{ 
  2.     events:{ 
  3.         load:function(){ 
  4.             var series = this.series[0] 
  5.             setInterval(function(){ 
  6.             $.getJSON('/data',function(res){ 
  7.                 $.each(res,function(i,v) { 
  8.                     series.addPoint(v) 
  9.                 }) 
  10.             }) 
  11.             },3000) 
  12.         } 
  13.     } 
  14. }, 
 

8、接下来启动django开发环境;

 
  1. cd memory 
  2. (py35env) [root@jupyter memory]# python manage.py runserver 0.0.0.0:8000 
  3. Performing system checks... 
  4.  
  5. System check identified no issues (0 silenced). 
  6. May 26, 2017 - 11:02:18 
  7. Django version 1.11.1, using settings 'memory.settings' 
  8. Starting development server at http://0.0.0.0:8000/ 
  9. Quit the server with CONTROL-C. 
 
然后通过浏览器就可以访问10.0.10.250:8000看到效果了;
 
这里调用的数据是上一篇 python 获取centos7的内存使用率并写入mysql   ,只要把monitor.py执行就可以看到动态的展现效果了。