make a python flask that will show cpu and ram usage with graph
- User
make a python flask that will show cpu and ram usage with graph
- Assistant
make a python flask that will show cpu and ram usage with graph
Sure! Below is a complete guide to creating a Python Flask application that monitors and displays CPU and RAM usage with dynamic graphs. We'll use the psutil library to gather system metrics and Chart.js for rendering the graphs on the frontend.
Here's how we'll structure the project:
cpu_ram_monitor/
├── app.py
├── templates/
│ └── index.html
├── static/
│ └── (optional static files like CSS or JS)
├── requirements.txt
First, create a project directory and navigate into it:
mkdir cpu_ram_monitor
cd cpu_ram_monitor
Create a requirements.txt file to list all dependencies:
touch requirements.txt
Add the following lines to requirements.txt:
Flask
psutil
Now, create a virtual environment and install the dependencies:
python3 -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
pip install -r requirements.txt
Create the main Flask application file app.py:
touch app.py
Add the following code to app.py:
from flask import Flask, render_template, jsonify
import psutil
import time
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/data')
def data():
cpu_percent = psutil.cpu_percent(interval=None)
ram = psutil.virtual_memory()
ram_percent = ram.percent
timestamp = int(time.time() * 1000) # Current time in milliseconds
return jsonify({
'cpu': cpu_percent,
'ram': ram_percent,
'time': timestamp
})
if __name__ == '__main__':
app.run(debug=True)
Explanation:
Routes:
/: Renders the main page (index.html)./data: Returns current CPU and RAM usage as JSON.Data Collection:
psutil.cpu_percent(interval=None): Gets the current CPU usage percentage.psutil.virtual_memory(): Retrieves RAM usage details.time.time(): Gets the current timestamp for graphing purposes.Create the templates directory and the index.html file:
mkdir templates
touch templates/index.html
Add the following code to templates/index.html:
Explanation:
fetchData function asynchronously fetches data from the /data endpoint.maxDataPoints) is reached, after which older data is removed to keep the graph updated in real-time.Note: For better real-time performance, consider using the chartjs-plugin-streaming plugin. However, in this example, we keep it simple without additional plugins.
Ensure you're in the project directory and the virtual environment is activated. Run the Flask application:
python app.py
By default, Flask runs on http://127.0.0.1:5000/. Open this URL in your web browser to view the CPU and RAM usage graphs updating in real-time.
For convenience, here's the complete code for each file.
app.pyfrom flask import Flask, render_template, jsonify
import psutil
import time
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/data')
def data():
cpu_percent = psutil.cpu_percent(interval=None)
ram = psutil.virtual_memory()
ram_percent = ram.percent
timestamp = int(time.time() * 1000) # Current time in milliseconds
return jsonify({
'cpu': cpu_percent,
'ram': ram_percent,
'time': timestamp
})
if __name__ == '__main__':
app.run(debug=True)
templates/index.htmlNote: I made some improvements to the index.html to utilize the time scale in Chart.js for better handling of time-based data.
requirements.txtFlask
psutil
Chart.js Streaming Plugin: For more efficient real-time graphing, consider using the Chart.js Streaming Plugin. This plugin is designed for real-time streaming data and can handle large datasets more gracefully.
Error Handling: The current implementation has basic error handling in the JavaScript fetchData function. Depending on your use case, you might want to add more robust error handling and user notifications.
Security: If deploying this application publicly, ensure to secure the endpoints and follow best practices for Flask applications.
Scaling: For monitoring multiple systems or more complex metrics, consider integrating with databases or more advanced visualization tools.
Feel free to customize and enhance the application according to your needs! If you encounter any issues or have further questions, feel free to ask.
Not yet included in a published release.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CPU and RAM Usage Monitor</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}
.chart-container {
width: 80%;
margin: auto;
}
canvas {
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Real-Time CPU and RAM Usage Monitor</h1>
<div class="chart-container">
<canvas id="cpuChart"></canvas>
</div>
<div class="chart-container">
<canvas id="ramChart"></canvas>
</div>
<script>
const cpuCtx = document.getElementById('cpuChart').getContext('2d');
const ramCtx = document.getElementById('ramChart').getContext('2d');
const maxDataPoints = 30;
const cpuData = {
labels: [],
datasets: [{
label: 'CPU Usage (%)',
data: [],
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
fill: true,
lineTension: 0.2,
}]
};
const ramData = {
labels: [],
datasets: [{
label: 'RAM Usage (%)',
data: [],
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
fill: true,
lineTension: 0.2,
}]
};
const cpuChart = new Chart(cpuCtx, {
type: 'line',
data: cpuData,
options: {
responsive: true,
scales: {
x: {
type: 'realtime',
realtime: {
delay: 2000,
onRefresh: fetchData,
}
},
y: {
beginAtZero: true,
max: 100
}
},
plugins: {
legend: { display: true }
}
}
});
const ramChart = new Chart(ramCtx, {
type: 'line',
data: ramData,
options: {
responsive: true,
scales: {
x: {
type: 'realtime',
realtime: {
delay: 2000,
onRefresh: fetchData,
}
},
y: {
beginAtZero: true,
max: 100
}
},
plugins: {
legend: { display: true }
}
}
});
async function fetchData(chart) {
const response = await fetch('/data');
const data = await response.json();
const time = new Date(data.time);
if (cpuData.labels.length > maxDataPoints) {
cpuData.labels.shift();
cpuData.datasets[0].data.shift();
ramData.labels.shift();
ramData.datasets[0].data.shift();
}
cpuData.labels.push(time.toLocaleTimeString());
cpuData.datasets[0].data.push(data.cpu);
ramData.labels.push(time.toLocaleTimeString());
ramData.datasets[0].data.push(data.ram);
chart.update('quiet');
}
setInterval(() => {
fetchData();
cpuChart.update();
ramChart.update();
}, 2000); // Fetch data every 2 seconds
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CPU and RAM Usage Monitor</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}
.chart-container {
width: 80%;
margin: auto;
}
canvas {
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Real-Time CPU and RAM Usage Monitor</h1>
<div class="chart-container">
<canvas id="cpuChart"></canvas>
</div>
<div class="chart-container">
<canvas id="ramChart"></canvas>
</div>
<script>
const cpuCtx = document.getElementById('cpuChart').getContext('2d');
const ramCtx = document.getElementById('ramChart').getContext('2d');
const maxDataPoints = 30;
const cpuData = {
labels: [],
datasets: [{
label: 'CPU Usage (%)',
data: [],
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
fill: true,
lineTension: 0.2,
}]
};
const ramData = {
labels: [],
datasets: [{
label: 'RAM Usage (%)',
data: [],
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
fill: true,
lineTension: 0.2,
}]
};
const cpuChart = new Chart(cpuCtx, {
type: 'line',
data: cpuData,
options: {
responsive: true,
scales: {
x: {
type: 'time',
time: {
unit: 'second',
displayFormats: {
second: 'h:mm:ss a'
}
},
title: {
display: true,
text: 'Time'
}
},
y: {
beginAtZero: true,
max: 100,
title: {
display: true,
text: 'Percentage (%)'
}
}
},
plugins: {
legend: { display: true }
}
}
});
const ramChart = new Chart(ramCtx, {
type: 'line',
data: ramData,
options: {
responsive: true,
scales: {
x: {
type: 'time',
time: {
unit: 'second',
displayFormats: {
second: 'h:mm:ss a'
}
},
title: {
display: true,
text: 'Time'
}
},
y: {
beginAtZero: true,
max: 100,
title: {
display: true,
text: 'Percentage (%)'
}
}
},
plugins: {
legend: { display: true }
}
}
});
async function fetchData() {
try {
const response = await fetch('/data');
const data = await response.json();
const time = new Date(data.time);
// Update CPU Chart
cpuData.labels.push(time);
cpuData.datasets[0].data.push(data.cpu);
if (cpuData.labels.length > maxDataPoints) {
cpuData.labels.shift();
cpuData.datasets[0].data.shift();
}
cpuChart.update();
// Update RAM Chart
ramData.labels.push(time);
ramData.datasets[0].data.push(data.ram);
if (ramData.labels.length > maxDataPoints) {
ramData.labels.shift();
ramData.datasets[0].data.shift();
}
ramChart.update();
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Fetch data every 2 seconds
setInterval(fetchData, 2000);
</script>
</body>
</html>