django——echarts(可視化)

如何使用echarts

echarts官網:https://www.echartsjs.com/zh/index.htmlhtml

cdn:https://www.bootcdn.cn/echarts/前端

實現可視化的通常方式

  • 服務器端處理:pyecharts
  • 後端負責給數據,前端拿到數據,本身渲染: echarts

django使用echars

  1. 要引入echarts.mim.js 或者是使用cdn
  2. 從官網的實例 https://www.echartsjs.com/examples/zh/index.html 找一個合適的示例
  3. 頁面中要定義一個標籤,設置一下長寬
    {% csrf_token %} <div class="row">
        <div class="col-md-4 page-header">
            <h1>用例執行狀況統計</h1>
            <div id="p1" style="max-width: 1000px;width: 900px;height:500px;max-height: 800px;"></div>
        </div>
    </div>
  4. 將示例拷貝到咱們前端頁面,放在function函數
  5. 使用ajax將後端將數據庫傳遞給前端,前端將數據替換到option的相對位置
    裏面的data數據須要從後端傳過來
    <script>
            function pieDoughnut(data) { var option = { tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' }, legend: { orient: 'vertical', left: 10, data: data[0], }, series: [ { name: '訪問來源', type: 'pie', radius: ['50%', '70%'], avoidLabelOverlap: false, label: { normal: { show: false, position: 'center' }, emphasis: { show: true, textStyle: { fontSize: '30', fontWeight: 'bold' } } }, labelLine: { normal: { show: false } }, data: data[1], } ] }; var myChart = echarts.init(document.getElementById('p1')); myChart.setOption(option); } window.onload = function () { $.ajax({ url: "/echarts_msg/", type: "POST", data: {"key": "value", "csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val()}, success: function (data) { pieDoughnut(data['pie_doughnut']); } }) } </script>
    js Code
  6. 而後在django的view.py中寫上以下內容:
     1 from django.http import JsonResponse  2 import echartsMsg  3 
     4 
     5 # ————————— 可視化相關 —————————
     6 def pie_doughnut():  7     # 它本身的數據,下面的是本身的數據,要作成它的數據結構
     8     # value = ''
     9     # name = ''
    10     # l = [
    11     # {value: 335, name: '直接訪問'}, # data
    12     # {value: 310, name: '郵件營銷'},
    13     # ]
    14 
    15     legend_data = ["已執行", "未執行"] 16     series_data = [ 17         {"value": 0, "name": "已執行"}, 18         {"value": 0, "name": "未執行"} 19  ] 20     api_obj = models.API.objects.all() 21     for api in api_obj: 22         series_data[0]['value'] += api.case_set.filter(case_execute_status=1).count() 23         series_data[1]['value'] += api.case_set.filter(case_execute_status=1).count() 24 
    25     return legend_data, series_data 26 
    27 def echarts_msg(request): 28     if request.method == "GET": 29         return render(request, "echarts_msg.html") 30     else: 31         pie_doughnut = echartsMsg.pie_doughnut() 32 
    33         return JsonResponse({ 34             "pie_doughnut": pie_doughnut, 35         })
    View.py Code

示例

在視圖函數中處理好相關數據:python

from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
def test(request):
    if request.method == "POST":
        obj = ([{'value': 3, 'name': '未執行'}, {'value': 8, 'name': '已執行'}], ['未執行', '已執行'])
        bar = [120, 200, 150, 80, 70, 110, 130]
        return JsonResponse({"obj": obj, 'bar': bar})
    else:

        return render(request, 'test.html', )

而後前端調用:jquery

<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>



<div id="Pie1" style="width: 400px;height:300px;"></div>
<div id="barSimple" style="width: 400px;height:300px;"></div>


</body>

<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/echarts/3.0.0/echarts.min.js"></script>
<script> // 餅圖 function Pie1(data, ) { var myChart = echarts.init(document.getElementById('Pie1')); option = { title: { text: '用例執行狀態統計', subtext: '', x: 'center' }, tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { orient: 'vertical', left: 'left', data: data[1] }, series: [ { name: '用例執行狀態', type: 'pie', radius: '55%', center: ['50%', '60%'], data:data[0], itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; myChart.setOption(option); } // 柱狀圖 function barSimple(data) { var myChart = echarts.init(document.getElementById('barSimple')); option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [{ data: data, type: 'bar' }] }; myChart.setOption(option) } window.onload = function () { $.ajax({ url: "/test/", type:"POST", data: {"k1": "v1"}, success: function (data) { // 餅圖 Pie1(data['obj']); // 柱狀圖 barSimple(data['bar']); console.log(data) } }) } </script>
</html>

效果:
ajax

相關文章
相關標籤/搜索