当前位置:   article > 正文

Django 配合Echarts绘制图表_django+echarts

django+echarts

在前面我总结了关于DjangoAdmin的使用技巧,利用DjangoAdmin这个后台管理功能,自己定制页面可以完成非常多的功能,下面我们将重点研究主机图形的绘制,展示和报表等功能的具体实现步骤,这里也算是个人的一点点经验。

定制查询图形功能

urls.py

  1. from django.contrib import admin
  2. from django.urls import path
  3. from MyWeb import views
  4. urlpatterns = [
  5. path('', admin.site.urls),
  6. path("grup/",views.grup)
  7. ]

views.py

  1. from django.shortcuts import render,HttpResponse
  2. def grup(request):
  3. if request.method == "POST":
  4. StartData = request.POST.get("StartData")
  5. EndData = request.POST.get("EndData")
  6. sel = request.POST.get("selec")
  7. print(StartData,EndData,sel)
  8. return render(request,"grup.html")

grup.html

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% block content %}
  4. <form action="/grup/" method="post">
  5. 开始时间: <input type="datetime-local" name="StartData" />
  6. 结束时间: <input type="datetime-local" name="EndData" />
  7. <select name="selec">
  8. <option value="CPU">CPU负载</option>
  9. <option value="Mem">内存负载</option>
  10. </select>
  11. <input type="submit" value="查询">
  12. </form>
  13. <br>
  14. <div id="main" style="width: 90%; height: 300px; border: 1px solid #eecc11; padding: 40px">
  15. <script src="http://echarts.baidu.com/dist/echarts.min.js"></script>
  16. <script>
  17. var mychart = echarts.init(document.getElementById("main"));
  18. var option = {
  19. xAxis: {
  20. type: 'category',
  21. data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  22. },
  23. yAxis: {
  24. type: 'value'
  25. },
  26. series: [{
  27. data: [820, 932, 901, 934, 1290, 1330, 1320],
  28. type: 'line'
  29. }]
  30. };
  31. mychart.setOption(option)
  32. </script>
  33. {% endblock %}

更新数据 为了方便后期内容,批量填充数据.

  1. import os,sys,sqlite3
  2. import time,psutil,datetime
  3. def GetCPU_Load(addr):
  4. dic = {}
  5. times = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M")
  6. cpu = psutil.cpu_percent(interval=None,percpu=True)
  7. dic["Address"] = addr
  8. dic["Times"] = times
  9. dic["load5"] = cpu[0]
  10. dic["load10"] = cpu[1]
  11. dic["load15"] = cpu[2]
  12. return dic
  13. if __name__ == "__main__":
  14. conn = sqlite3.connect("db.sqlite3")
  15. cursor = conn.cursor()
  16. while True:
  17. dic = GetCPU_Load("192.168.1.1")
  18. insert = 'insert into MyWeb_cpu(Address,Times,load5,load10,load15) values("{}","{}","{}","{}","{}")'.\
  19. format(dic["Address"],dic["Times"],dic["load5"],dic["load10"],dic["load15"])
  20. print(insert)
  21. cursor.execute(insert)
  22. conn.commit()
  23. time.sleep(1)

来看下数据库的设计。

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% load static %}
  4. {% block title %}{{ site_title|default:_('Django site admin') }}{% endblock %}
  5. {% block content %}
  6. <form action="/cpu/" method="post">
  7. 主机地址: <input type="text" name="Address" />
  8. 开始时间: <input type="datetime-local" name="StartData" />
  9. 结束时间: <input type="datetime-local" name="EndData" />
  10. <select name="selec">
  11. <option value="CPU">CPU负载</option>
  12. <option value="Mem">内存负载</option>
  13. </select>
  14. <input type="submit" value="查询">
  15. </form>
  16. {{ time }}
  17. {{ load }}
  1. from django.shortcuts import render,HttpResponse
  2. from MyWeb import models
  3. import time,datetime
  4. def cpu(request):
  5. if request.method == "POST":
  6. times = []
  7. load = []
  8. Address = request.POST.get("Address")
  9. StartData = request.POST.get("StartData")
  10. EndData = request.POST.get("EndData")
  11. ret = models.CPU.objects.raw('select * from MyWeb_cpu where Times>="{}" and Times <="{}";'.
  12. format(StartData,EndData))
  13. for item in ret:
  14. times.append(item.Times.split("T")[1])
  15. load.append(item.load5)
  16. return render(request,"index.html",{"time":times,"load":load})

有个问题,没有解决,可能得用json发数据。

最后没找到解决方法,应该是要用json序列化一下就好。

  1. <!--name: index.html-->
  2. {% extends "admin/base_site.html" %}
  3. {% load i18n static %}
  4. {% load static %}
  5. {% block title %}{{ site_title|default:_('Django site admin') }}{% endblock %}
  6. {% block content %}
  7. <form action="/cpu/" method="post">
  8. 开始时间: <input type="datetime-local" name="StartData" />
  9. 结束时间: <input type="datetime-local" name="EndData" />
  10. <select name="selec">
  11. <option value="CPU">CPU Load5 负载</option>
  12. </select>
  13. <input type="submit" value="检索图形">
  14. </form>
  15. <div id="main" style="width: 90%; height: 300px; border: 1px solid #eecc11; padding: 40px">
  16. <script src="http://echarts.baidu.com/dist/echarts.min.js"></script>
  17. <script>
  18. var mychart = echarts.init(document.getElementById("main"));
  19. var option = {
  20. grid:{
  21. top:"50px",
  22. left:"50px",
  23. right:"15px",
  24. bottom:"50px"
  25. },
  26. xAxis: {
  27. type: 'category',
  28. data: {{ cpu_data }}
  29. },
  30. yAxis: {
  31. type: 'value'
  32. },
  33. series: [{
  34. type: 'line',
  35. data: {{ cpu_data }}
  36. }]
  37. };
  38. mychart.setOption(option)
  39. </script>
  40. {% endblock %}

顺便加上IP查询功能,则更加完整了。

上方form表单提交后会自动清除表单内容,如果不想清空,可以使用ajax方式提交,或使用一下方法来完成.

  1. {% block content %}
  2. <form action="/fw/" method="post" target="not_iframe">
  3. <input type="text" name="user"/>
  4. <input type="submit" value="提交">
  5. </form>
  6. <iframe id="id_iframe" name="not_iframe" style="display:none;"></iframe>
  7. {% endblock %}

本机仪表盘

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% load static %}
  4. {% block title %}{{ site_title|default:_('Django site admin') }}{% endblock %}
  5. {% block content %}
  6. <div id="cpuChart" style="width: 32%; height: 380px; border: 1px solid #dddddd; float:left; margin-right: 8px;"></div>
  7. <div id="memChart" style="width: 32%; height: 380px; border: 1px solid #dddddd; float:left; margin-right: 8px;"></div>
  8. <div id="diskChart" style="width: 32%; height: 380px; border: 1px solid #dddddd; float:left; margin-right: 8px;"></div>
  9. <script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script>
  10. <script>
  11. var cpuChart = echarts.init(document.getElementById("cpuChart"));
  12. var option = {
  13. series: [
  14. {
  15. type: 'gauge',
  16. detail: {formatter: '{value}%'},
  17. data: [{value: 44, name: 'CPU 利用率'}]
  18. }
  19. ]
  20. };cpuChart.setOption(option, true);
  21. </script>
  22. <script>
  23. var memChart = echarts.init(document.getElementById("memChart"));
  24. var option = {
  25. series: [
  26. {
  27. type: 'gauge',
  28. detail: {formatter: '{value}%'},
  29. data: [{value: 25, name: '内存利用率'}]
  30. }
  31. ]
  32. };memChart.setOption(option, true);
  33. </script>
  34. <script>
  35. var diskChart = echarts.init(document.getElementById("diskChart"));
  36. var option = {
  37. series: [
  38. {
  39. type: 'gauge',
  40. detail: {formatter: '{value}%'},
  41. data: [{value: 18, name: '磁盘使用量'}]
  42. }
  43. ]
  44. };diskChart.setOption(option, true);
  45. </script>
  46. {% endblock %}

增加自定义页面(本机图形监控): 除了默认页面可以使用以外,还可以自己创造一个新页面.

  1. <!--name: index.html(本机仪表盘)-->
  2. {% extends "admin/base_site.html" %}
  3. {% load i18n static %}
  4. {% load static %}
  5. {% block title %}{{ site_title|default:_('Django site admin') }}{% endblock %}
  6. {% block content %}
  7. <div id="cpuChart" style="width: 32%; height: 380px; border: 1px solid #dddddd; float:left; margin-right: 8px;"></div>
  8. <div id="memChart" style="width: 32%; height: 380px; border: 1px solid #dddddd; float:left; margin-right: 8px;"></div>
  9. <div id="diskChart" style="width: 32%; height: 380px; border: 1px solid #dddddd; float:left; margin-right: 8px;"></div>
  10. <script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script>
  11. <script>
  12. var cpuChart = echarts.init(document.getElementById("cpuChart"));
  13. var option = {
  14. series: [
  15. {
  16. type: 'gauge',
  17. detail: {formatter: '{value}%'},
  18. data: [{value: 44, name: 'CPU 利用率'}]
  19. }
  20. ]
  21. };cpuChart.setOption(option, true);
  22. </script>
  23. <script>
  24. var memChart = echarts.init(document.getElementById("memChart"));
  25. var option = {
  26. series: [
  27. {
  28. type: 'gauge',
  29. detail: {formatter: '{value}%'},
  30. data: [{value: 25, name: '内存利用率'}]
  31. }
  32. ]
  33. };memChart.setOption(option, true);
  34. </script>
  35. <script>
  36. var diskChart = echarts.init(document.getElementById("diskChart"));
  37. var option = {
  38. series: [
  39. {
  40. type: 'gauge',
  41. detail: {formatter: '{value}%'},
  42. data: [{value: 18, name: '磁盘使用量'}]
  43. }
  44. ]
  45. };diskChart.setOption(option, true);
  46. </script>
  47. {% endblock %}

动态监控平台(折线图)

绘图

  1. <div id="echo" style="width: 100%; height: 400px; "></div>
  2. <script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
  3. <script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script>
  4. <script type="text/javascript" charset="UTF-8">
  5. var display = function(time,cpu1,cpu5,cpu15){
  6. var echo =echarts.init(document.getElementById("echo"));
  7. var option = {
  8. // tooltip 鼠标放上去之后会自动出现坐标
  9. tooltip: {
  10. trigger: 'axis',
  11. axisPointer: {
  12. type: 'cross',
  13. label: {
  14. backgroundColor: '#6a7985'
  15. }
  16. }
  17. },// toolbox = 菜单栏中的各种小功能
  18. toolbox: {
  19. feature: {
  20. dataZoom: {
  21. yAxisIndex: 'none'
  22. },
  23. restore: {},
  24. saveAsImage: {}
  25. }
  26. },
  27. legend: {
  28. data: [ '1分钟负载', '5分钟负载', '15分钟负载']
  29. },
  30. xAxis: {
  31. type: 'category',
  32. data: time
  33. },
  34. yAxis: {
  35. type: 'value'
  36. },
  37. series: [
  38. {
  39. name: "1分钟负载",
  40. stack: "总量",
  41. data: cpu1,
  42. type: 'line'
  43. },
  44. {
  45. name: "5分钟负载",
  46. stack: "总量",
  47. data: cpu5,
  48. type: 'line'
  49. },
  50. {
  51. name: "15分钟负载",
  52. stack: "总量",
  53. data: cpu15,
  54. type: 'line'
  55. }
  56. ]
  57. };
  58. echo.setOption(option,true);
  59. };
  60. </script>

另一种刷新式绘图

  1. <script type="text/javascript" src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script>
  2. <div id="main" style="height:500px;width:1200px;border:1px solid #eecc11;padding:10px;"></div>
  3. <script type="text/javascript" charset="UTF-8">
  4. var display = function(time,cpu){
  5. // 负责初始化绘图画布
  6. var myChart = echarts.init(document.getElementById('main'));
  7. myChart.setOption({
  8. title: {
  9. text: '监控系统CPU资源'
  10. },
  11. tooltip: {},
  12. xAxis: {
  13. data: []
  14. },
  15. yAxis: {},
  16. series: [{
  17. name: 'cpu',
  18. type: 'line',
  19. data: []
  20. }]
  21. });
  22. // 下方就是给指定字段填充数据
  23. myChart.setOption({
  24. xAxis: {
  25. data: time
  26. },
  27. series: [{
  28. name: 'cpu', // 根据名字对应到相应的系列
  29. data: cpu
  30. }]
  31. });
  32. };
  33. // 首次显示加载动画
  34. myChart.showLoading();
  35. </script>

数据处理

  1. // 负责对参数的解析
  2. var time =["","","","","","","","","",""];
  3. var cpu1 = [0,0,0,0,0,0,0,0,0,0];
  4. var cpu5 = [0,0,0,0,0,0,0,0,0,0];
  5. var cpu15 = [0,0,0,0,0,0,0,0,0,0];
  6. var update = function(recv){
  7. time.push(recv.response[0]);
  8. cpu1.push(parseFloat(recv.response[1]));
  9. cpu5.push(parseFloat(recv.response[2]));
  10. cpu15.push(parseFloat(recv.response[3]));
  11. if(time.length >=10){
  12. time.shift();
  13. cpu1.shift();
  14. cpu5.shift();
  15. cpu15.shift();
  16. display(time,cpu1,cpu5,cpu15)
  17. }
  18. };

图形更新

  1. $(
  2. function () {
  3. fetchData();
  4. setInterval(fetchData, 1000);
  5. }
  6. );
  7. function fetchData(){
  8. $.ajax({
  9. url:"/_ajax/",
  10. type:"GET",
  11. dataType: 'json',
  12. success:function (recv) {
  13. update(recv);
  14. }
  15. })
  16. }

view.py

  1. from django.shortcuts import render,HttpResponse
  2. import os,subprocess,time,json
  3. def index(request):
  4. return render(request,"index.html")
  5. def ajax(request):
  6. if request.method == "GET":
  7. data = []
  8. data.append(time.strftime("%M:%S", time.localtime()))
  9. for key in ["system.cpu.util[,,avg1]", "system.cpu.util[,,avg5]", "system.cpu.util[,,avg15]"]:
  10. cmd = "C:/get.exe -s {} -p {} -k {}".format("192.168.1.20", "10050", key)
  11. proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
  12. data.append(float(proc.stdout.readlines()[0].split()[0]))
  13. return HttpResponse(json.dumps({"response":data}))

urls.py

  1. from django.contrib import admin
  2. from django.urls import path
  3. from MyWeb import views
  4. urlpatterns = [
  5. path('admin/', admin.site.urls),
  6. path("cpu/",views.index),
  7. path("_ajax/",views.ajax)
  8. ]

可能效果不是很明显,你可以稍微改一下代码。

  1. def ajax(request):
  2. if request.method == "GET":
  3. data = []
  4. data.append(time.strftime("%M:%S", time.localtime()))
  5. data.append(random.randint(1,100))
  6. data.append(random.randint(100, 200))
  7. data.append(random.randint(23, 90))
  8. return HttpResponse(json.dumps({"response":data}))
  1. // 负责对参数的解析
  2. var time =["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""];
  3. var cpu1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
  4. var cpu5 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
  5. var cpu15 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
  6. var update = function(recv){
  7. time.push(recv.response[0]);
  8. cpu1.push(parseFloat(recv.response[1]));
  9. cpu5.push(parseFloat(recv.response[2]));
  10. cpu15.push(parseFloat(recv.response[3]));
  11. if(time.length >=40){
  12. time.shift();
  13. cpu1.shift();
  14. cpu5.shift();
  15. cpu15.shift();
  16. display(time,cpu1,cpu5,cpu15)
  17. }
  18. };

除了可以监控系统负载外,还可以监控网卡,监控内存等,原理都是一样的,网卡监控代码。

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% load static %}
  4. {% block content %}
  5. <div id="main" style="width: 100%; height: 400px;"></div>
  6. <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  7. <script type="text/javascript" src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script>
  8. <script type="text/javascript" charset="UTF-8">
  9. var display = function(){
  10. var main =echarts.init(document.getElementById("main"));
  11. var option = {
  12. // tooltip 鼠标放上去之后会自动出现坐标
  13. tooltip: {
  14. trigger: 'axis',
  15. axisPointer: {
  16. type: 'cross',
  17. label: {
  18. backgroundColor: '#6a7985'
  19. }
  20. }
  21. },// toolbox = 菜单栏中的各种小功能
  22. toolbox: {
  23. feature: {
  24. dataZoom: {
  25. yAxisIndex: 'none'
  26. },
  27. restore: {},
  28. saveAsImage: {}
  29. }
  30. },
  31. legend: {
  32. data: [ '网卡入口流量', '网卡出口流量']
  33. },
  34. // 负责绘图的配置
  35. xAxis: {
  36. type: 'category',
  37. data: [1,2,3,4,5,1,2,3,4,5]
  38. },
  39. yAxis: {
  40. type: 'value'
  41. },
  42. series: [
  43. {
  44. name: "网卡入口流量",
  45. stack: "总量",
  46. data: [1,2,3,4,5,1,2,3,4,5],
  47. type: 'line',
  48. areaStyle: {}
  49. },
  50. {
  51. name: "网卡出口流量",
  52. stack: "总量",
  53. data: [1,2,3,4,5,1,2,3,4,5],
  54. type: 'line',
  55. areaStyle: {}
  56. }
  57. ]
  58. };
  59. main.setOption(option,true);
  60. };
  61. display()
  62. </script>
  63. {% endblock %}

网站流量统计(折线图)

通过分析日志统计流量。

  1. import os,sys
  2. def log(path):
  3. key = []
  4. value = []
  5. for item in fp.readlines():
  6. date = item.split()[3]
  7. HourData = date.split(":")[1] + ":" + date.split(":")[2]
  8. if item.split()[9] != "-" and item.split()[9] != '"-"':
  9. SendByte = int(item.split()[9])
  10. key.append(HourData)
  11. value.append(SendByte)
  12. return dict(zip(key,value))
  13. fp = open("c://access.log","r")
  14. dic = log(fp)

针对Web服务的流量统计 上面代码只能统计出所有的流量,无法叠加,可以以IP为例进行流量叠加。

  1. import os,sys
  2. def Count_IP_And_Flow(file):
  3. addr = {} # key 保存当前的IP信息
  4. flow = {} # value 保存当前IP流量总和
  5. Count= 0 # 针对IP地址的计数器
  6. with open(file) as f:
  7. contexts = f.readlines()
  8. for line in contexts:
  9. if line.split()[9] != "-" and line.split()[9] != '"-"':
  10. size = line.split()[9]
  11. ip_attr = line.split()[0]
  12. Count = int(size) + Count
  13. if ip_attr in addr.keys():
  14. addr[ip_attr] = addr[ip_attr] + 1
  15. flow[ip_attr] = flow[ip_attr] + int(size)
  16. else:
  17. addr[ip_attr] = 1
  18. flow[ip_attr] = int(size)
  19. return addr,flow
  20. if __name__ == "__main__":
  21. Address,OutFlow = Count_IP_And_Flow("c://access.log")
  22. print("地址计数:{} ---> 流量计数:{}".format(Address,OutFlow))

上面的代码,稍微修改一下就能统计时间与流量的关系。

  1. def Count_IP_And_Flow(file):
  2. addr = {} # key 保存当前的IP信息
  3. flow = {} # value 保存当前IP流量总和
  4. Count= 0 # 针对IP地址的计数器
  5. with open(file) as f:
  6. contexts = f.readlines()
  7. for line in contexts:
  8. if line.split()[9] != "-" and line.split()[9] != '"-"':
  9. size = line.split()[9]
  10. temp = line.split()[3]
  11. ip_attr = temp.split(":")[1] + ":" + temp.split(":")[2]
  12. Count = int(size) + Count
  13. if ip_attr in addr.keys():
  14. addr[ip_attr] = addr[ip_attr] + 1
  15. flow[ip_attr] = flow[ip_attr] + int(size)
  16. else:
  17. addr[ip_attr] = 1
  18. flow[ip_attr] = int(size)
  19. return addr,flow
  20. if __name__ == "__main__":
  21. Address,OutFlow = Count_IP_And_Flow("c://access.log")
  22. print("流量计数:{}".format(Address,OutFlow))

接着是绘图,这里直接把代码拿出来吧。

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% load static %}
  4. {% block content %}
  5. <link rel="stylesheet" href="https://www.blib.cn/cdn/bootstrap3.css">
  6. <div class="panel panel-primary" style="width: 100%;height: 30%; float: left">
  7. <div class="panel-heading">
  8. <h3 class="panel-title">网站流量统计</h3>
  9. </div>
  10. <div class="panel-body">
  11. <div id="main" style="width:100%; height: 400px"></div>
  12. </div>
  13. </div>
  14. <script src="https://www.blib.cn/cdn/echarts.js" type="text/javascript"></script>
  15. <script src="https://www.blib.cn/cdn/jquery.js" type="text/javascript"></script>
  16. <script type="text/javascript" charset="UTF-8">
  17. var kv = new Array();
  18. var keys = new Array();
  19. var values = new Array();
  20. kv = {{ data | safe }};
  21. for(var logkey in kv){
  22. keys.push(logkey);
  23. values.push(kv[logkey]);
  24. }
  25. var display = function() {
  26. var main = echarts.init(document.getElementById("main"));
  27. var option = {
  28. xAxis: {
  29. type: 'category',
  30. boundaryGap: false,
  31. data: keys
  32. },
  33. yAxis: {
  34. type: 'value'
  35. },
  36. series: [{
  37. data: values,
  38. type: 'line',
  39. areaStyle: {},
  40. }]
  41. };
  42. main.setOption(option,true);
  43. };
  44. display();
  45. </script>
  46. {% endblock %}
  1. from django.shortcuts import render
  2. import json
  3. def Count_IP_And_Flow(file):
  4. addr = {} # key 保存当前的IP信息
  5. flow = {} # value 保存当前IP流量总和
  6. Count= 0 # 针对IP地址的计数器
  7. with open(file) as f:
  8. contexts = f.readlines()
  9. for line in contexts:
  10. if line.split()[9] != "-" and line.split()[9] != '"-"':
  11. size = line.split()[9]
  12. temp = line.split()[3]
  13. ip_attr = temp.split(":")[1] + ":" + temp.split(":")[2]
  14. Count = int(size) + Count
  15. if ip_attr in addr.keys():
  16. flow[ip_attr] = flow[ip_attr] + int(size)
  17. else:
  18. addr[ip_attr] = 1
  19. flow[ip_attr] = int(size)
  20. return flow
  21. def index(request):
  22. OutFlow = Count_IP_And_Flow("c://access.log")
  23. print(OutFlow)
  24. return render(request,"index.html",{"data":json.dumps(OutFlow)})

效果图如下,我这台机器访问量很小,将就着看吧。

统计IP出现的次数。

  1. def IP_Count(file):
  2. ip = {}
  3. with open(file) as f:
  4. for i in f.readlines():
  5. ip_attr = i.strip().split()[0]
  6. if ip_attr in ip.keys():
  7. ip[ip_attr] = ip[ip_attr] + 1
  8. else:
  9. ip[ip_attr] = 1
  10. print(ip)
  11. IP_Count("c://access.log")

网站状态码统计(饼状图)

饼状图的绘制: 统计目标主机网页状态码,与个数,并绘制饼状图,饼图和其他图不太一样,绘制起来蛮烦一些。

  1. from django.shortcuts import render
  2. import json
  3. def Count_Flag_And_Flow(file):
  4. list = []
  5. flag = {}
  6. with open(file) as f:
  7. contexts = f.readlines()
  8. for line in contexts:
  9. it = line.split()[8]
  10. list.append(it)
  11. list_num = set(list)
  12. for item in list_num:
  13. num = list.count(item)
  14. flag[item] = num
  15. return flag
  16. def index(request):
  17. Address = Count_Flag_And_Flow("c://access.log")
  18. print(Address)
  19. return render(request,"index.html",{"data":json.dumps(Address)})
  20. from MyWeb import views
  21. urlpatterns = [
  22. path('admin/', admin.site.urls),
  23. path("log/",views.index)
  24. ]
  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% load static %}
  4. {% block content %}
  5. <div id="main" style="width:50%; height: 300px"></div>
  6. <script src="https://www.blib.cn/cdn/echarts.js" type="text/javascript"></script>
  7. <script src="https://www.blib.cn/cdn/jquery.js" type="text/javascript"></script>
  8. <script type="text/javascript" charset="UTF-8">
  9. var kv = new Array();
  10. kv = {{ data | safe }}
  11. var test = new Array();
  12. for(var logkey in kv){
  13. test.push( {value:kv[logkey], name:logkey} )
  14. }
  15. var display = function(){
  16. var main = echarts.init(document.getElementById("main"));
  17. var option = {
  18. legend: {
  19. orient: 'vertical',
  20. left: 'left',
  21. },
  22. series: [
  23. {
  24. type: 'pie',
  25. radius: '70%',
  26. center: ['50%', '50%'],
  27. detail: {formatter:'{value}'},
  28. data: test
  29. }
  30. ]
  31. };
  32. main.setOption(option,true);
  33. };
  34. display();
  35. </script>
  36. {% endblock %}

加上框架看效果。

  1. <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
  2. <div class="panel panel-primary" style="width: 60%;height: 50%">
  3. <div class="panel-heading">
  4. <h3 class="panel-title">网站访问状态统计</h3>
  5. </div>
  6. <div class="panel-body">
  7. 这是一个基本的面板
  8. </div>
  9. </div>

来,搞事

  1. <link rel="stylesheet" href="https://www.blib.cn/cdn/bootstrap3.css">
  2. <div class="panel panel-primary" style="width: 40%;height: 30%">
  3. <div class="panel-heading">
  4. <h3 class="panel-title">网站访问状态统计</h3>
  5. </div>
  6. <div class="panel-body">
  7. <div id="main" style="width:100%; height: 300px"></div>
  8. </div>
  9. </div>

网站访问设备统计(柱状图)

统计设备的类型,例如Windows linux 等,这里我们接着上面的做吧,先来改布局。

  1. {% block content %}
  2. <link rel="stylesheet" href="https://www.blib.cn/cdn/bootstrap3.css">
  3. <div class="panel panel-primary" style="width: 40%;height: 30%;float: left">
  4. <div class="panel-heading">
  5. <h3 class="panel-title">网站访问状态统计</h3>
  6. </div>
  7. <div class="panel-body">
  8. <div id="main" style="width:100%; height: 300px"></div>
  9. </div>
  10. </div>
  11. <div class="panel panel-primary" style="width: 58%;height: 30%; float: right">
  12. <div class="panel-heading">
  13. <h3 class="panel-title">网站设备类型统计</h3>
  14. </div>
  15. <div class="panel-body">
  16. <div id="main1" style="width:100%; height: 300px"></div>
  17. </div>
  18. </div>

完整代码如下,就是拼接起来就行,没什么技术含量。

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% load static %}
  4. {% block content %}
  5. <link rel="stylesheet" href="https://www.blib.cn/cdn/bootstrap3.css">
  6. <div class="panel panel-primary" style="width: 40%;height: 30%;float: left">
  7. <div class="panel-heading">
  8. <h3 class="panel-title">网站访问状态统计</h3>
  9. </div>
  10. <div class="panel-body">
  11. <div id="main" style="width:100%; height: 300px"></div>
  12. </div>
  13. </div>
  14. <div class="panel panel-primary" style="width: 58%;height: 30%; float: right">
  15. <div class="panel-heading">
  16. <h3 class="panel-title">网站设备类型统计</h3>
  17. </div>
  18. <div class="panel-body">
  19. <div id="main1" style="width:100%; height: 300px"></div>
  20. </div>
  21. </div>
  22. <script src="https://www.blib.cn/cdn/echarts.js" type="text/javascript"></script>
  23. <script src="https://www.blib.cn/cdn/jquery.js" type="text/javascript"></script>
  24. <script type="text/javascript" charset="UTF-8">
  25. var kv = new Array();
  26. kv = {{ data | safe }}
  27. var test = new Array();
  28. for(var logkey in kv){
  29. test.push( {value:kv[logkey], name:logkey} )
  30. }
  31. var display = function(){
  32. var main = echarts.init(document.getElementById("main"));
  33. var option = {
  34. legend: {
  35. orient: 'vertical',
  36. left: 'left',
  37. },
  38. series: [
  39. {
  40. type: 'pie',
  41. radius: '70%',
  42. center: ['50%', '50%'],
  43. detail: {formatter:'{value}'},
  44. data: test
  45. }
  46. ]
  47. };
  48. main.setOption(option,true);
  49. };
  50. display();
  51. </script>
  52. <script type="text/javascript" charset="UTF-8">
  53. var display = function() {
  54. var main1 = echarts.init(document.getElementById("main1"));
  55. var option = {
  56. xAxis: {
  57. type: 'category',
  58. data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  59. },
  60. yAxis: {
  61. type: 'value'
  62. },
  63. series: [{
  64. data: [120, 200, 150, 80, 70, 110, 130],
  65. type: 'bar'
  66. }]
  67. };
  68. main1.setOption(option,true);
  69. };
  70. display();
  71. </script>
  72. {% endblock %}

  1. import os,sys
  2. def Count_Flag_And_Type(file):
  3. list = []
  4. flag = {}
  5. with open(file) as f:
  6. contexts = f.readlines()
  7. for line in contexts:
  8. list.append( line.split()[12].replace("(",""))
  9. list_num = set(list)
  10. for item in list_num:
  11. num = list.count(item)
  12. flag[item] = num
  13. return flag
  14. if __name__ == "__main__":
  15. a = Count_Flag_And_Type("c://access.log")
  16. print(a)

最终代码如下,前端第二个拼接位置需要注意。

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% load static %}
  4. {% block content %}
  5. <link rel="stylesheet" href="https://cdn.lyshark.com/cdn/bootstrap3.css">
  6. <div class="panel panel-primary" style="width: 40%;height: 30%;float: left">
  7. <div class="panel-heading">
  8. <h3 class="panel-title">网站访问状态统计</h3>
  9. </div>
  10. <div class="panel-body">
  11. <div id="main" style="width:100%; height: 300px"></div>
  12. </div>
  13. </div>
  14. <div class="panel panel-primary" style="width: 58%;height: 30%; float: right">
  15. <div class="panel-heading">
  16. <h3 class="panel-title">网站设备类型统计</h3>
  17. </div>
  18. <div class="panel-body">
  19. <div id="main1" style="width:100%; height: 300px"></div>
  20. </div>
  21. </div>
  22. <script src="https://cdn.lyshark.com/cdn/echarts.js" type="text/javascript"></script>
  23. <script src="https://cdn.lyshark.com/cdn/jquery.js" type="text/javascript"></script>
  24. <script type="text/javascript" charset="UTF-8">
  25. var kv = new Array();
  26. kv = {{ data | safe }}
  27. var test = new Array();
  28. for(var logkey in kv){
  29. test.push( {value:kv[logkey], name:logkey} )
  30. }
  31. var display = function(){
  32. var main = echarts.init(document.getElementById("main"));
  33. var option = {
  34. legend: {
  35. orient: 'vertical',
  36. left: 'left',
  37. },
  38. series: [
  39. {
  40. type: 'pie',
  41. radius: '70%',
  42. center: ['50%', '50%'],
  43. detail: {formatter:'{value}'},
  44. data: test
  45. }
  46. ]
  47. };
  48. main.setOption(option,true);
  49. };
  50. display();
  51. </script>
  52. <script type="text/javascript" charset="UTF-8">
  53. var kv = new Array();
  54. kv = {{ data1 | safe }}
  55. var keys = new Array();
  56. var values = new Array();
  57. for(var logkey in kv){
  58. keys.push(logkey);
  59. values.push(kv[logkey]);
  60. }
  61. console.log(keys,values);
  62. var display = function() {
  63. var main1 = echarts.init(document.getElementById("main1"));
  64. var option = {
  65. xAxis: {
  66. type: 'category',
  67. data: keys
  68. },
  69. yAxis: {
  70. type: 'value'
  71. },
  72. series: [{
  73. data: values,
  74. type: 'bar'
  75. }]
  76. };
  77. main1.setOption(option,true);
  78. };
  79. display();
  80. </script>
  81. {% endblock %}

后端处理日志并返回结果。

  1. from django.shortcuts import render
  2. import json
  3. def Count_Flag_And_Flow(file):
  4. list = []
  5. flag = {}
  6. with open(file) as f:
  7. contexts = f.readlines()
  8. for line in contexts:
  9. it = line.split()[8]
  10. list.append(it)
  11. list_num = set(list)
  12. for item in list_num:
  13. num = list.count(item)
  14. flag[item] = num
  15. return flag
  16. def Count_Flag_And_Type(file):
  17. list = []
  18. flag = {}
  19. with open(file) as f:
  20. contexts = f.readlines()
  21. for line in contexts:
  22. list.append( line.split()[12].replace("(",""))
  23. list_num = set(list)
  24. for item in list_num:
  25. num = list.count(item)
  26. flag[item] = num
  27. return flag
  28. def index(request):
  29. Address = Count_Flag_And_Flow("c://access.log")
  30. print(Address)
  31. Types = Count_Flag_And_Type("c://access.log")
  32. print(Types)
  33. return render(request,"index.html",{"data":json.dumps(Address),"data1":json.dumps(Types)})
  34. def mob(request):
  35. return render(request,"mob.html")

经过测试上面的代码有一定的局限性,比如下面的这两条代码,会出现异常。

::1 - - [15/Jan/2020:04:43:40 -0500] "OPTIONS * "
192.168.1.2 - - [15/Jan/2020:04:37:09 -0500] "-" 408 - "-" "-"

日志统计时,应该避免出现这种无效行,该怎么做,我就不说了,正则!!

单位时间访客(访客位置)

先来几个API查询地址。

http://ip.ws.126.net/ipquery?ip=192.168.1.100

  1. import os,sys
  2. import urllib.request
  3. def counts(file):
  4. Addr = []
  5. with open(file) as f:
  6. contexts = f.readlines()
  7. for line in contexts:
  8. lt = line.split()[0]
  9. if lt !="::1" and lt !="127.0.0.1":
  10. Addr.append(lt)
  11. return set(Addr)
  12. if __name__ == "__main__":
  13. ret = counts("C://access.log")
  14. for item in ret:
  15. url = "http://ip.ws.126.net/ipquery?ip={}".format(item)
  16. ret = urllib.request.urlopen(url)
  17. print(ret.read().decode('gbk'))

  1. if __name__ == "__main__":
  2. ret = counts("C://access.log")
  3. for item in ret:
  4. url = "http://ip.ws.126.net/ipquery?ip={}".format(item)
  5. ret = urllib.request.urlopen(url).read().decode('gbk')
  6. City = ret.split()[5].replace('province:"', '').replace('"}', "")
  7. print("IP:{} -----> 城市:{}".format(item,City))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/164999
推荐阅读
相关标签
  

闽ICP备14008679号