prof-rossetti / intro-to-python

An Introduction to Programming in Python
Other
97 stars 244 forks source link

Flask - Pass Data to JavaScript #91

Open s2t2 opened 3 years ago

s2t2 commented 3 years ago

Here is an example of passing some python data to the page, and accessing it via JavaScript, for example to make a dataviz. Uses the plotly JavaScript library.

Route:

@home_routes.route("/")
@home_routes.route("/home")
def index():
    print("HOME...")
    data = [
        {"date":"2021-01-01", "score": 100},
        {"date":"2021-01-02", "score": 90},
        {"date":"2021-01-03", "score": 120}
    ]
    print(data)
    return render_template("home.html", data=data)

Template:

{% extends "bootstrap_5_layout.html" %}
{% set active_page = "home" %}

{% block content %}

    <h1>Welcome Home</h1>

    <p>This is a paragraph on the "home" page.</p>

    <div id="chart-container">
    </div>

    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script type="text/javascript">

        var data = JSON.parse('{{ data|tojson }}')
        console.log("DATA:", data)
        console.log(data[0])

        console.log("MAKING SOME CHARTS...")

        // TODO: make a chart

        //
        // EXAMPLE CHART
        // see: https://plotly.com/javascript/bar-charts/
        // ...  https://plotly.com/javascript/horizontal-bar-charts/
        //
        // var data = [
        //     {
        //         x: ['giraffes', 'orangutans', 'monkeys'],
        //         y: [20, 14, 23],
        //         type: 'bar'
        //     }
        // ]
        // Plotly.newPlot('bar-chart-container', data)

        // IMPLEMENTATION

        console.log("BAR DATA", data)

        var dates = data.map(obj => obj["date"])
        var scores = data.map(obj => obj["score"])
        console.log("DATES", dates)
        console.log("SCORES", scores)

        var data = [
            {
                x: dates,
                y: scores,
                type: 'bar',
                //orientation: 'h'
            }
        ]
        Plotly.newPlot('chart-container', data)

    </script>
{% endblock %}

Page Preview:

Screen Shot 2021-08-08 at 11 25 46 AM