从python flask应用程序动态填充图表数据

时间:2014-12-18 00:37:14

标签: javascript python flask amcharts

我正在使用amCharts javascript库在Web浏览器上放置图表。

以下是HTML文件中的javascript代码:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>amCharts examples</title>
    <link rel="stylesheet" href="style.css" type="text/css">
    <script src="../amcharts/amcharts.js" type="text/javascript"></script>
    <script src="../amcharts/serial.js" type="text/javascript"></script>
    <script type="text/javascript">
        var chart;

        var chartData = [
            {
                "year": 2003,
                "europe": 2.5,
                "namerica": 2.5,
                "asia": 2.1,
                "lamerica": 0.3,
                "meast": 0.2,
                "africa": 0.1
            },
            {
                "year": 2004,
                "europe": 2.6,
                "namerica": 2.7,
                "asia": 2.2,
                "lamerica": 0.3,
                "meast": 0.3,
                "africa": 0.1
            },
            {
                "year": 2005,
                "europe": 2.8,
                "namerica": 2.9,
                "asia": 2.4,
                "lamerica": 0.3,
                "meast": 0.3,
                "africa": 0.1
            }
        ];

        AmCharts.ready(function () {
            // SERIALL CHART
            chart = new AmCharts.AmSerialChart();
            chart.dataProvider = chartData;
            chart.categoryField = "year";
            chart.plotAreaBorderAlpha = 0.2;
            chart.rotate = true;

            // AXES
            // Category
            var categoryAxis = chart.categoryAxis;
            categoryAxis.gridAlpha = 0.1;
            categoryAxis.axisAlpha = 0;
            categoryAxis.gridPosition = "start";

            // value
            var valueAxis = new AmCharts.ValueAxis();
            valueAxis.stackType = "regular";
            valueAxis.gridAlpha = 0.1;
            valueAxis.axisAlpha = 0;
            chart.addValueAxis(valueAxis);

            // GRAPHS
            // firstgraph
            var graph = new AmCharts.AmGraph();
            graph.title = "Europe";
            graph.labelText = "[[value]]";
            graph.valueField = "europe";
            graph.type = "column";
            graph.lineAlpha = 0;
            graph.fillAlphas = 1;
            graph.lineColor = "#C72C95";
            graph.balloonText = "<b><span style='color:#C72C95'>[[title]]</b></span><br><span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>";
            graph.labelPosition = "middle";
            chart.addGraph(graph);

            // second graph
            graph = new AmCharts.AmGraph();
            graph.title = "North America";
            graph.labelText = "[[value]]";
            graph.valueField = "namerica";
            graph.type = "column";
            graph.lineAlpha = 0;
            graph.fillAlphas = 1;
            graph.lineColor = "#D8E0BD";
            graph.balloonText = "<b><span style='color:#afbb86'>[[title]]</b></span><br><span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>";
            graph.labelPosition = "middle";
            chart.addGraph(graph);

            // third graph
            graph = new AmCharts.AmGraph();
            graph.title = "Asia-Pacific";
            graph.labelText = "[[value]]";
            graph.valueField = "asia";
            graph.type = "column";
            graph.lineAlpha = 0;
            graph.fillAlphas = 1;
            graph.lineColor = "#B3DBD4";
            graph.balloonText = "<b><span style='color:#74bdb0'>[[title]]</b></span><br><span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>";
            graph.labelPosition = "middle";
            chart.addGraph(graph);

            // fourth graph
            graph = new AmCharts.AmGraph();
            graph.title = "Latin America";
            graph.labelText = "[[value]]";
            graph.valueField = "lamerica";
            graph.type = "column";
            graph.lineAlpha = 0;
            graph.fillAlphas = 1;
            graph.lineColor = "#69A55C";
            graph.balloonText = "<b><span style='color:#69A55C'>[[title]]</b></span><br><span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>";
            graph.labelPosition = "middle";
            chart.addGraph(graph);

            // fifth graph
            graph = new AmCharts.AmGraph();
            graph.title = "Middle-East";
            graph.labelText = "[[value]]";
            graph.valueField = "meast";
            graph.type = "column";
            graph.lineAlpha = 0;
            graph.fillAlphas = 1;
            graph.lineColor = "#B5B8D3";
            graph.balloonText = "<b><span style='color:#7a81be'>[[title]]</b></span><br><span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>";
            graph.labelPosition = "middle";
            chart.addGraph(graph);

            // sixth graph
            graph = new AmCharts.AmGraph();
            graph.title = "Africa";
            graph.labelText = "[[value]]";
            graph.valueField = "africa";
            graph.type = "column";
            graph.lineAlpha = 0;
            graph.fillAlphas = 1;
            graph.lineColor = "#F4E23B";
            graph.balloonText = "<b><span style='color:#c3b218'>[[title]]</b></span><br><span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>";
            graph.labelPosition = "middle";
            chart.addGraph(graph);

            // LEGEND
            var legend = new AmCharts.AmLegend();
            legend.position = "right";
            legend.borderAlpha = 0.3;
            legend.horizontalGap = 10;
            legend.switchType = "v";
            chart.addLegend(legend);

            chart.creditsPosition = "top-right";

            // WRITE
            chart.write("chartdiv");
        });

        // Make chart 2D/3D
        function setDepth() {
            if (document.getElementById("rb1").checked) {
                chart.depth3D = 0;
                chart.angle = 0;
            } else {
                chart.depth3D = 20;
                chart.angle = 30;
            }
            chart.validateNow();
        }
    </script>
</head>

<body>
    <div id="chartdiv" style="width: 100%; height: 400px;"></div>
    <div style="margin-left:40px;">
        <input type="radio" checked="true" name="group" id="rb1" onclick="setDepth()">2D
        <input type="radio" name="group" id="rb2" onclick="setDepth()">3D
    </div>
</body>

我希望以一种similar to this方式从我的Python Flask应用程序中填充chartData的值:

"""
This file is part of the flask+d3 Hello World project.
"""
import json
import flask
import numpy as np


app = flask.Flask(__name__)


@app.route("/")
def index():
    """
    When you request the root path, you'll get the index.html template.
    """
    return flask.render_template("index.html")


@app.route("/data")
@app.route("/data/<int:ndata>")
def data(ndata=100):
    """
    On request, this returns a list of ``ndata`` randomly made data points.
    :param ndata: (optional)
        The number of data points to return.
    :returns data:
        A JSON string of ``ndata`` data points.
    """
    x = 10 * np.random.rand(ndata) - 5
    y = 0.5 * x + 0.5 * np.random.randn(ndata)
    A = 10. ** np.random.rand(ndata)
    c = np.random.rand(ndata)
    return json.dumps([{"_id": i, "x": x[i], "y": y[i], "area": A[i],
        "color": c[i]}
        for i in range(ndata)])


if __name__ == "__main__":
    import os

    port = 8000

    # Open a web browser pointing at the app.
    os.system("open http://localhost:{0}".format(port))

    # Set up the development server on port 8000.
    app.debug = True
    app.run(port=port)

我希望data()填充图表数据。

但是我在HTML文件中调用JS来捕获那些数据。类似于d3.json()的东西?

1 个答案:

答案 0 :(得分:0)

如果要在模板的HTML中嵌入JavaScript,最好的方法是在Flask中计算所需的所有值,然后将它们传递给模板。

我不知道您的应用逻辑是您的数据库,所以我只是从上面的代码中复制一些值。无论如何文件看起来应该是这样的:

@app.route("/data")
def data():

    # sample data
    chart_data = [
        {
            "year": 2003,
            "europe": 2.5,
            "namerica": 2.5,
            "asia": 2.1,
            "lamerica": 0.3,
            "meast": 0.2,
            "africa": 0.1
        },
        {
            "year": 2003,
            "europe": 2.5,
            "namerica": 2.5,
            "asia": 2.1,
            "lamerica": 0.3,
            "meast": 0.2,
            "africa": 0.1
        }]

    # pass the data do the template
    return render_template('chart.html', chart_data=chart_data)

您的模板在JavaScript块中使用此列表进行迭代:

...
var chartData = [
{{ for chart in chart_data }}
    {
        "year": {{ chart.year }},
        "europe": {{ chart.europe }},
        "namerica": {{ chart.namerica }},
        "asia": {{ chart.asia }},
        "lamerica": {{ chart.lamerica }},
        "meast": {{ chart.meast }},
        "africa": {{ chart.africa }}
    }
    {{ if not loop.last }} , {{ endif }}
{{ endfor }}
]

AmCharts.ready(function () {
    // SERIALL CHART
    ...