pyecharts在django中的一个例子

 

 

 

 

 

url

    url(r'^grid/$', ChartView.as_view(), name='grid'),
    url(r'domain_overview/$', domain_overview),

 

 

views

from django.http import HttpResponse
from pyecharts import options as opts
from pyecharts.charts import Line, Bar, Pie
from pyecharts.globals import ThemeType
from rest_framework.views import APIView
 
# 图表的布局, Page垂直布局,Grid水平布局
from pyecharts.charts import Page, Grid
 
 
def response_as_json(data):
    json_str = json.dumps(data)
    response = HttpResponse(
        json_str,
        content_type="application/json",
    )
    response["Access-Control-Allow-Origin"] = "*"
    return response


def json_response(data, code=200):
    data = {
        "code": code,
        "msg": "success",
        "data": data,
    }
    return response_as_json(data)


def json_error(error_string="error", code=500, **kwargs):
    data = {
        "code": code,
        "msg": error_string,
        "data": {}
    }
    data.update(kwargs)
    return response_as_json(data)


JsonResponse = json_response
JsonError = json_error

#def domain_overview(request):
def grid_base() -> Grid:
    g_num = DomainName.objects.filter(account__name="godaddy-huangjun").count()
    a_num = DomainName.objects.filter(account__name="aliyun-主账号").count()
    n_num = DomainName.objects.filter(account__name="networksolution").count()
    x_num = DomainName.objects.filter(account__name="xinnet").count()
    num_list = [a_num, x_num, g_num, n_num]
    name_list = ['aliyun', 'xinnet', 'godaddy', 'networksolution']

    # 找出即将过期的10个域名
    target = DomainName.objects.order_by("expiredTime").values("name", "expiredTime")[:8]
    name_list2 = []
    time_list2 = []
    now =datetime.now()
    #name_list2 = ["abvvv.com", "baaaaa.vip", "cdgagadg.abc","ddfagasga.iot", "efefaef", "fadfasdf.xyz", "gfwqdfasf.net", "hfasdf"]
    #time_list2 = ["10", "10", "10", "23", "12", "23", "13", "45"]
    for x in target:
        name = x.get("name")
        time = x.get("expiredTime").replace(tzinfo=None)
        day_left = str((time-now).days)
        name_list2.append(name)
        time_list2.append(day_left)


    #page_1 = Page(layout=Page.SimplePageLayout)
    #grid1_1 = Grid(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width='1350px'))

    # 饼图
    # pie1 = (
    #         Pie(init_opts=opts.InitOpts(theme=ThemeType.ROMA))
            
    #             .add("", list(zip(name_list, num_list)),
    #                 radius=["20%", "25%"],  # 控制内外半径,即图的大小
    #                 #rosetype="radius",  # 表明是玫瑰图,半径跟数值挂钩
    #                 center=["35%", "35%"])  # 饼图中心的位置,即整个图的位置。格式:[左右,上下]

    #             .set_global_opts(title_opts=opts.TitleOpts(title="域名分布", subtitle="", pos_left='25%',pos_top="10%"),
    #                             legend_opts=opts.LegendOpts(pos_left="20%",pos_bottom="40%"))

    #             .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}\n{d}%"))
    #     )

    
    # 创建柱状图
    bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
    bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.MACARONS))
    # 增加主题和副标题
    bar.set_global_opts(
        title_opts=opts.TitleOpts(title="域名分布", pos_left="7%", pos_top="10%"), 
        legend_opts=opts.LegendOpts(pos_left="15%", pos_top="10%")
        )
    # 添加柱状图的数据
    bar.add_xaxis(name_list)
    bar.add_yaxis("数量", num_list, category_gap="50%")

    
   
    # # 增加最大值,最小值
    # bar.set_series_opts(markpoint_opts=opts.MarkPointOpts(data=[
    #     opts.MarkPointItem(name="最大值", type_="max"),
    #     opts.MarkPointItem(name="最小值", type_="min")
    # ]))

    # 折线图
    line = (
        # 创建折线图
        Line()
            # 增加主标题与副标题
            .set_global_opts(title_opts=opts.TitleOpts(title="10个即将到期的域名", pos_right="45%", pos_top="10%"),
            legend_opts=opts.LegendOpts(pos_right="25%"),
            yaxis_opts=opts.AxisOpts(name="")
            )
            # x轴标签
            .add_xaxis(name_list2)
            # 增加折线图数据, symbol_size:圆点的大小,is_smooth:是否圆滑曲线,color:曲线的颜色
            # 注意:当上面的init_opts设置了主题样式后,color就不起作用了
            .add_yaxis("", time_list2, symbol_size=10, is_smooth=True, color="green",
                       markpoint_opts=opts.MarkPointOpts(data=[
                           
                           opts.MarkPointItem(name="最小值", type_="min")]))

    )



    grid_chart = (
        Grid()
            .add(bar, grid_opts=opts.GridOpts(pos_right="70%", pos_bottom="52%", pos_top="22%" ))
            .add(line, grid_opts=opts.GridOpts(pos_left="45%", pos_right = "35%", pos_bottom="52%", pos_top="22%"))
            #.add(pie1, grid_opts=opts.GridOpts(pos_left="25%"))
            .dump_options_with_quotes()
    )
    return grid_chart

class ChartView(APIView):
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(grid_base()))

@login_required
def domain_overview(request):
    return render(request, 'assets/domain_overview.html', locals())
 

 

前端 domain_overview.html

{% extends 'base.html' %}
{% load bootstrap %}



{% block page-content %}

<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>

<div class="row">
  <div class="col-md-12 col-sm-12 col-xs-12">
    <div class="x_panel">
      <div class="x_title">
        <h2><i class="fa fa-bars"></i> 域名概览 <small></small></h2>
        
        <div class="ibox-tools">
            <a class="collapse-link">
                    <i class="fa fa-chevron-up"></i>
            </a>
            <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                    <i class="fa fa-wrench"></i>
            </a>
            <ul class="dropdown-menu dropdown-user"></ul>
            <a class="close-link">
                    <i class="fa fa-times"></i>
            </a>
        </div>
        <label/>
        <div id="grid" style="width:1350px; height:750px; background: white;"></div>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
    var chart = echarts.init(document.getElementById('grid'), 'white', {renderer: 'canvas'});

    function fetchData() {
        $.ajax({
            type: "GET",
            url: "/assets/grid",  #/assets是上层url
            dataType: 'json',
            success: function (result) {
                chart.setOption(result.data);
            }
        });
    }
    jQuery(function($) {
        fetchData(chart);
    });

</script>

 {% endblock page-content %}

 

posted @ 2021-04-25 11:21  坚强的小蚂蚁  阅读(501)  评论(0编辑  收藏  举报