Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

python - Call a Flask function every few minutes

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...