1
votes

On my HTML page I've got a span that gets the value of the function getStatus():

<span id="sysStatus" style="font-weight: bold;">{{ status }}</span>

The function that returns status:

def getStatus():
    state = database().getState()
    if state:
        status = " On"
    else:
        status = "Off"
    return status

Rendering the html page:

class Tongles(flask.views.MethodView):
    def get(self):
        return flask.render_template('page.html', status=getStatus())

I would like somehow to dynamically refresh the status of the system, and the text on the span.

How can I recall the function getStatus without reloading the whole page?

1
Flask applications are different than normal Python apps. Cause they have to update and the HTML part. I can easily execute the Python function every few minutes, but the point its to dynamically update the span text which is an indication for the user. - Bobys
Theoretical solution: make a special flask handler to return specifically the status then in client side please ajax to query the status periodically. - chfw
You could either use sockets or poll the server for getStatus using AJAX requests. - adarsh

1 Answers

7
votes

flask_app.py add a route to your getStatus method

...
@app.route("/myStatus")
def getStatus():
    state = database().getState()
    if state:
        status = " On"
    else:
        status = "Off"
    return status
 ...

page.html use ajax callbacks to populate the div with jquery(or something else if you want)

...

<span id="sysStatus" style="font-weight: bold;">{{ status }}</span>

...
...

<script>
$(document).ready(function() {
    setInterval("ajaxd()",10000); // call every 10 seconds
});

function ajaxd() { 
  //reload result into element with id "sysStatus"
  $("#sysStatus").load("/myStatus", function() {  alert( "Load was performed." ); });

}
</script>

...