使用Python的Flask框架,结合Highchart,动态渲染图表

服务端动态渲染图表

参考文章链接:https://www.highcharts.com.cn/docs/dynamic-produce-html-page

参考文章是使用php写的,我这边改用python写

具体如下:

1.目录结构:

ajax_demo
    ajax_demo.py
    templates
        -index.html
    static
        -jquery-3.3.1.min.js
        -highcharts-7.0.3.js

2.ajax_demo.py

from flask import Flask,render_template

app = Flask(__name__)


@app.route('/')
def index():
    data = {
        'text1':'对数折线图',
        'data1':[1, 2, 4, 8, 16, 32, 64, 128, 256, 512],
    }
    return render_template('index.html',**data)

if __name__ == '__main__':
    app.run(debug=True)

3..index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个 Highcharts 图表</title>
    <!-- 引入 jquery.js -->
    <script src="static/jquery-3.3.1.min.js"></script>
    <!-- 引入 highcharts.js -->
    <script src="static/highcharts-7.0.3.js"></script>


</head>
<body>

<!-- 图表容器 DOM -->
<div id="container" style="min-500px;height:500px"></div>

<script>
    var chart = Highcharts.chart('container', {
        title: {
            text: '{{ text1 }}'
        },
        xAxis: {
            tickInterval: 1
        },
        yAxis: {
            type: 'logarithmic',
            minorTickInterval: 0.1
        },
        tooltip: {
            headerFormat: '<b>{series.name}</b><br />',
            pointFormat: 'x = {point.x}, y = {point.y}'
        },
        series: [{
            data: {{ data1 }},
            pointStart: 1
        }]
    });

</script>

</body>
</html>

注意:series中的data使用的是{{ data1 }}方式,没有加引号,但是title中的text使用的是'{{ text1 }}'的方式,加的有引号。后者若不加引号,则不显示图表。

其他参数估计也类是,凡是字符串的数据,从服务端传递过来数据,都需要加上引号。

原文地址:https://www.cnblogs.com/sanduzxcvbnm/p/10423556.html