Building Dashboards with Flask and Chart.js (Intermediate)

Building Dashboards with Flask and Chart.js (Intermediate)
Written by
Wilco team
December 17, 2024
Tags
No items found.
Building Dashboards with Flask and Chart.js

Building Dashboards with Flask and Chart.js

In this blog post, we will explore how to build interactive dashboards using Flask and Chart.js. We'll dive into the world of web development, focusing on creating data-driven web applications with real-time updates and user interactions.

Setting Up a Flask Application

Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications.


# Import flask module in the project
from flask import Flask

# Initialize the flask app
app = Flask(__name__)

# Define a basic route
@app.route('/')
def home():
    return "Hello, World!"

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

Connecting Flask to a Database

We will be using SQLite as our database. SQLite is a C library that provides a lightweight disk-based database. It doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language.


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

@app.route("/")
def index():
    return "Hello, World!"

if __name__ == "__main__":
    db.create_all()
    app.run(debug=True)

Integrating Chart.js for Dynamic Data Visualization

Chart.js is a JavaScript library that allows you to draw different types of charts by using the HTML5 canvas element. It supports 8 different chart types: bar, line, area, pie/doughnut, radar, bubble, and scatter.


new Chart(document.getElementById("bar-chart"), {
    type: 'bar',
    data: {
      labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
      datasets: [
        {
        label: "Population (millions)",
        backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
        data: [2478,5267,734,784,433]
        }
      ]
    }
});

Implementing Real-Time Data Updates and User Interactions in the Dashboard

Updating charts in real-time is a powerful feature that allows you to display live data that changes over time. In this section, we will show you how to update a chart in real-time using Flask and Chart.js.


@app.route("/data")
def return_data():
    # Query the database for the latest data
    data = db.session.query(Table).order_by(Table.id.desc()).first()

    # Return the data in a format suitable for Chart.js
    return jsonify({
        "labels": ["Temperature", "Humidity"],
        "datasets": [{
            "label": "Sensor Data",
            "data": [data.temperature, data.humidity]
        }]
    })

Top 10 Key Takeaways

  1. Flask is a lightweight WSGI web application framework, perfect for small to complex applications.
  2. SQLite is an excellent choice for a lightweight disk-based database.
  3. Chart.js is a versatile library for creating various types of charts.
  4. Flask-SQLAlchemy is a Flask extension that simplifies the use of SQLAlchemy in your Flask application.
  5. Creating a real-time dashboard involves querying the data at specific intervals and updating the charts.
  6. Use the jsonify function in Flask to return JSON responses.
  7. The Chart.js library uses the HTML5 canvas element to draw charts.
  8. Always remember to create all your database tables before running your Flask application.
  9. Remember to handle any errors that may occur during database operations.
  10. Ensure your Flask application is properly configured before deployment.

Ready to start learning? Start the quest now

Other posts on our blog
No items found.