How can you display the results of a script in real-time for a Django 1.4 website?

放肆的年华 提交于 2021-02-16 05:33:02

问题


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.


回答1:


You first approach won't work because you need to use streaming responses which were first added in Django 1.5.

A proper solution needs some kind of long running connection which streams the data. Before you do this, you need to think about resources and how many users you intend to support. You also need to define 'real-time' more explicitly - how many updates per second do you actually need to see? You are potentially tying up a lot of resources to serve this data continuously.

Assuming not too many users, and updates up to every second, one solution is to use polling. You have two view functions:

  1. One view serves a static page that includes some javascript
  2. The javascript makes an AJAX request (every second, say) to get the updated data from a second view, and displays it on the page.

If you want it more than every second, the best solution is use to use WebSockets - so you'd have some javascript that opens a websocket connection to get the new data. This generally does not work well with Django, but can be made to work using things like fanout.io - see the blog post.

Another solution is swampdragon - they have a tutorial for building a CPU monitor. This uses Tornado, a Python server much better suited to real-time applications.


A simple example using fanout:

Web page:

<script src="http://pubsub.fanout.io/static/faye-browser-min.js"></script>
<div id="output"></div>

<script>
var client = new Faye.Client('http://pubsub.fanout.io/r/59f4bc8c/bayeux');
client.subscribe('/test', function (data) {
    $('#output').text(data);
});
</script>

See it in jsfiddle

Python script - simply run on your server:

#!/usr/bin/env python

# pip install psutil
# pip install fanout

import fanout
import psutil
import time

fanout.realm = '59f4bc8c'
fanout.key = '81gUakHNM/Y7+1V0BkmErw=='

while True:
    fanout.publish('test', 'CPU percent: {0}%'.format(psutil.cpu_percent()))
    time.sleep(1)

This is using my test realm on fanout. It will actually work as it is at the time of posting, but you'll need to substitute your own key/realm etc. in normal situation. There is no need to use Django at all - it does not help.

Instead of using psutil, you could of course use SAR or the output of a script:

data = file("measurements.txt").read()
fanout.publish("test", data)

To get the data from a system command (e.g. procinfo), use:

import subprocess
data = subprocess.check_output(["procinfo"])



回答2:


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.




回答3:


It sounds like you'll have an easier time if you parse your SAR data into a database for easy querying in your view.

You might also take a look at the subprocess module in Python. It allows for executing external processes.




回答4:


maybe from your import is nothing what your import again.

from django.shortcuts render

Try this:
from django.shortcuts import render



来源:https://stackoverflow.com/questions/28045050/how-can-you-display-the-results-of-a-script-in-real-time-for-a-django-1-4-websit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!