old_gold_mountain
old_gold_mountain

Reputation: 9

Regularly update data in HTML from python script using flask

I'm trying to get a python script to regularly push the current time to an HTML page using Flask. (This is not my end goal, it's just a very simple version of the problem I'm trying to solve.) I can't seem to get the JavaScript to continuously request updated data from the Python script. What am I doing wrong? This code is largely pieced together from similar questions posted before, but I still can't figure out how to get it to work.

Python code:

from flask import Flask, render_template
from datetime import datetime

app = Flask(__name__)

@app.route("/")
def template_test():
    return render_template('template.html')

@app.route('/get_time', methods= ['GET', 'POST'])
def stuff():
    result = datetime.utcnow()
    return jsonify(result=result)

if __name__ == '__main__':
    app.run(debug=True)

HTML:

<html>
  <body>
    <p id="result">Time goes here</p>
    <script>
    setInterval(
      function()
      {
         $.getJSON(
            $SCRIPT_ROOT + '/get_time',
            {},                     
            function(data)
            {
              $("#result").text(data.result);
            });
      },
      500);
      </script>
  </body>
</html>

Upvotes: 0

Views: 1633

Answers (1)

RobF
RobF

Reputation: 221

Is that your HTML in its entirety? I ask because while your script looks okay to me, you're using jQuery commands but don't appear to be importing the jQuery library itself.

Adding <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script></head> in between your <html> and <body> tags at the top of the file should help.

Also, it's not really required in a case this simple, but it's good practice when using jQuery to enclose your script in $(document).ready(function() { your_script_here }); - this will execute it once the document has loaded completely, so you don't risk trying to carry out operations on elements that haven't loaded or rendered yet in more complex documents.

Upvotes: 1

Related Questions