1-Django - 使用Echarts

about

Echarts
Echarts是一个非常优秀的可视化框架,由百度开源,提供了非常丰富的图表类型。

Github地址:https://github.com/apache/incubator-echarts
官网地址:echartsjs.com/zh/index.html

用过echarts的同学都知道,它提供了一个叫setOptions的方法,通过这个方法我们传入一个options就可以生成一个图表了。
对开发者而言,这是非常方便的,我们只需维护这个options变量就OK了。

pyecharts
pyecharts是一款将echarts封装到python中的一款开源框架,由国内几个大哥写的,源码拜读了些许,感觉封装的很有层次感,pythonic十足。

Github地址: https://github.com/pyecharts/pyecharts
官网地址: https://pyecharts.org/#/zh-cn/

示例

django4.2.3 + python3.10 + echarts5.4.3

urls.py

from django.contrib import admin
from django.urls import path
from api import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('charts/', views.charts),
]

在视图函数中处理好相关数据:

import psutil   # pip install psutil,https://www.cnblogs.com/Neeo/articles/10935844.html
from django.shortcuts import render
from django.http import JsonResponse

def hum_convert(value):
    """
    自适应转换单位
    https://www.cnblogs.com/0506winds/p/13953600.html
    """
    units = ["B", "KB", "MB", "GB", "TB", "PB"]
    size = 1024.0
    for i in range(len(units)):
        if (value / size) < 1:
            # return "%.2f%s" % (value, units[i])
            return "%.2f" % value
        value = value / size
def charts(request):
    if request.method == "GET":
        return render(request, 'charts.html')
    else:
        cpu_bar = ""
        li = list(psutil.cpu_percent(interval=1, percpu=True))
        li.sort(reverse=True)
        for index, item in enumerate(li[:10], 1):
            print(item)
            cpu_bar += """
            <div>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" aria-valuenow="{}" aria-valuemin="0" aria-valuemax="100"
                         style="min-width: 2em;width: {}%;">
                        {}%
                    </div>
                </div>
            </div>
            """.format(item, item, item)
        data = {
            "memory": {
                'title': ['total', 'available', 'percent', 'used', 'free'],
                'content': [hum_convert(i) for i in list(psutil.virtual_memory())],
                "percent": list(psutil.virtual_memory())[2],
            },
            "cpu": {
                "cpu_bar": cpu_bar,
                'avg_percent': psutil.cpu_percent() * 10
            }
        }
        return JsonResponse(data)

然后前端调用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
</head>
<body>
{% csrf_token %}
<div>
    <div class="container">
        <div class="row">
            <h3>内存使用率</h3>
            <div class="col-lg-6">
                <div id="bar-simple" style="width: 600px;height:400px;"></div>
            </div>
            <div class="col-lg-6">
                <div id="memory-gauge-simple" style="width: 600px;height:400px;"></div>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <h3>CPU使用率</h3>
        <div class="col-lg-6" id="cpu_bar"></div>
        <div class="col-lg-6">
            <div id="cpu_per" style="width: 600px;height:400px;"></div>
        </div>
    </div>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
<script src="http://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script>

    function memory(data) {
        var barchartDom = document.getElementById('bar-simple');
        var barmyChart = echarts.init(barchartDom);
        var baroption;
        baroption = {
            title: {
                show: true,
                text: "内存使用情况,单位GB",
            },
            xAxis: {
                type: 'category',
                data: data['title']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: data['content'],
                    type: 'bar'
                }
            ]
        };
        baroption && barmyChart.setOption(baroption);

        var gaugechartDom = document.getElementById('memory-gauge-simple');
        var gaugemyChart = echarts.init(gaugechartDom);
        var gaugeoption;

        gaugeoption = {
            tooltip: {
                formatter: '{a} <br/>{b} : {c}%'
            },
            series: [
                {
                    name: 'Pressure',
                    type: 'gauge',
                    progress: {
                        show: true
                    },
                    detail: {
                        valueAnimation: true,
                        formatter: '{value}'
                    },
                    data: [
                        {
                            value: data['percent'],
                            name: '内存使用率(%)'
                        }
                    ]
                }
            ]
        };

        gaugeoption && gaugemyChart.setOption(gaugeoption);


    }

    function cpu(data) {
        $("#cpu_bar").html(data['cpu_bar']);
        let chartDom = document.getElementById('cpu_per');
        var myChart = echarts.init(chartDom);
        let option;
        option = {
            tooltip: {
                formatter: '{a} <br/>{b} : {c}%'
            },
            series: [
                {
                    name: 'Pressure',
                    type: 'gauge',
                    progress: {
                        show: true
                    },
                    detail: {
                        valueAnimation: true,
                        formatter: '{value}'
                    },
                    data: [
                        {
                            value: data['avg_percent'],
                            name: 'AVG(%)'
                        }
                    ]
                }
            ]
        };
        option && myChart.setOption(option);

    }
    window.onload = function () {
        setInterval(() => {
            // console.log(111, data)
            $.ajax({
                url: "/charts/",
                type: "POST",
                data: {"csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val()},
                success: function (data) {
                    console.log(111, data)
                    // CPU使用情况
                    cpu(data['cpu'])
                    memory(data['memory'])


                }
            })
        }, 5000)
    }
</script>
</html>

效果:


欢迎斧正,that's all

see also:

echarts和pyecharts复用options

posted @ 2020-01-06 14:26  听雨危楼  阅读(8312)  评论(2编辑  收藏  举报