So after finding out how to display the results of scripts on a Django website, I thought I'd be able to display the likes of live CPU information using SAR however whenever I change my code and refresh the webpage it doesn't load up and constantly looks like it's trying to load the webpage.
The only thing I've managed so far is to run the SAR command in a terminal, parse the results to a text file and then print out the text file using
import os
from django.shortcuts import render
def dashboard(request):
output = os.popen('cat measurements.txt').read()
return render(request,'dashboard/geckoboard.html', {'output': output})
However this doesn't give me live data, just whatever was the most recent recording at the time of refreshing the webpage.
What I want is to be able to monitor the performance in real time. I think I've seen in the past where you can go through a static file and pretend it's live for demos but that's not what I need.
After doing some research and asking people I know who have done similar tasks, I was recommended to use AJAX to solve this problem. Here's the code I used.
function cpu_system() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("cpu-system").innerHTML=xmlhttp.responseText;
}
}
setInterval(function() {
xmlhttp.open("POST","/static/stats/%system.txt",true);
xmlhttp.send();
}, 5000);
}
So in this function, I was sending the data from my %system.txt file every 5 seconds. Whenever I wanted to get live results I just can a sar script which sent the %system data to the %system.txt file.