Prerequisites
- Python 3.x: Ensure Python is installed.
- Flask: You can install it using pip:bashCopy code
pip install Flask
- Flask-CORS: For cross-origin resource sharing:bashCopy code
pip install Flask-CORS
Step 1: Setting Up the Flask Backend
Create a file named app.py
for the backend.
pythonCopy codefrom flask import Flask, jsonify
from flask_cors import CORS
import random
app = Flask(__name__)
CORS(app)
# Dummy data generation
def generate_data():
return {
"likes": random.randint(100, 1000),
"shares": random.randint(50, 500),
"comments": random.randint(10, 100),
"followers": random.randint(1000, 5000),
}
@app.route('/api/metrics', methods=['GET'])
def get_metrics():
metrics = generate_data()
return jsonify(metrics)
if __name__ == '__main__':
app.run(debug=True)
Step 2: Creating the Frontend
Create a folder named static
and add an index.html
file inside it.
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Social Media Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h1>Social Media Dashboard</h1>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
async function fetchMetrics() {
const response = await fetch('http://127.0.0.1:5000/api/metrics');
const data = await response.json();
return data;
}
async function renderChart() {
const data = await fetchMetrics();
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Likes', 'Shares', 'Comments', 'Followers'],
datasets: [{
label: 'Engagement Metrics',
data: [data.likes, data.shares, data.comments, data.followers],
backgroundColor: [
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
renderChart();
</script>
</body>
</html>
Step 3: Running the Application
- Open your terminal and navigate to the folder where
app.py
is located. - Run the Flask application:bashCopy code
python app.py
- Open a web browser and go to
http://127.0.0.1:5000/static/index.html
.
Explanation
- Backend: The Flask app serves a simple API endpoint
/api/metrics
that returns random engagement metrics in JSON format. - Frontend: The HTML file fetches data from the Flask API and uses Chart.js to render a bar chart of the metrics.
Extending the Dashboard
- Data Source: Replace the random data generation with real data from social media APIs (e.g., Twitter, Facebook).
- Styling: Use CSS frameworks like Bootstrap to style the dashboard.
- More Features: Add user authentication, historical data tracking, and real-time updates.
Leave a Reply