What is the best way to implement a forced page refresh using Flask?


I have a large number of fields that will be updating real time from an external process. I would like to update the Flask hosted pages periodically to show connected users any changes. Ideally the whole page would not refresh, this was a complaint of a similar system, but rather just update a number of fields on the page.

Current Direction
My current thoughts is to use possibly use a JavaScript to handle this, but I'm not sure if that's even possible when using Flask.

Is there a way with Flask, or 3rd party module, to accomplish this?

Additional Information
The data will be updated using various sockets and serial ports. Each interface will be running in its own thread and updating shared memory. Note that the Flask / web interface has read-only writes to shared memory that can be updated by the other threads.

The total client pool should never exceed 20 people. This is a web interface to a test system and in general will only have 1-5 people connected to it at any given time.

12/12/2011 7:01:08 AM

Accepted Answer

To avoid refreshing the entire page you want to use what is called AJAX. It looks like this is easy to implement in flask.

Since you want it to happen periodically you need to call your AJAX functions from a timer function in javascript.

This means you just put the javascript from the flask page inside a timer call.

Here's approximately what the javascript would look like:

setInterval(                               //Periodically 
     $.getJSON(                            //Get some values from the server
        $SCRIPT_ROOT + '/get_values',      // At this URL
        {},                                // With no extra parameters
        function(data)                     // And when you get a response
          $("#result").text(data.result);  // Write the results into the 
                                           // #result element
  500);                                    // And do it every 500ms
12/12/2011 6:28:33 AM

I think probably the easiest way to do this is using javascript as you already suggest in your question. In this case, Flask would be just delivering an HTML document that contains some javascript code to be executed by the browser, so I don't see why this could cause any problem to Flask. In this page, I've found some examples using different combinations such as using a timer (which seems to be what you're looking for).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow