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.
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)
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)
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]
}
]
}
});
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]
}]
})
Ready to start learning? Start the quest now