Trying to get realtime sensor data from python into html using Flask and jquery without refreshing entire page Trying to get realtime sensor data from python into html using Flask and jquery without refreshing entire page flask flask

Trying to get realtime sensor data from python into html using Flask and jquery without refreshing entire page


Your python code return the entire page of index.html upon receiving each request from the browser, what you should do is instead of return render_template('index.html', **templateData), you only return the data with something like return jsonify(templateData), 200. In order to do this, create a separate route for handling the request.

#! /usr/bin/python3from flask import Flask, render_template, jsonifyapp = Flask(__name__)EMULATE_HX711=FalsereferenceUnit = 1if not EMULATE_HX711:   import RPi.GPIO as GPIO   from hx711 import HX711else:   from emulated_hx711 import HX711hx = HX711(5, 6)hx.set_reading_format("MSB", "MSB")hx.set_reference_unit(-23000)#this clears the data on startup hx.reset()hx.tare()# this route only handle the rendering of index.html@app.route("/main")def main():   return render_template('index.html')# this route handling the request send to the /update uri@app.route("/update")def update():    val = hx.get_weight(5)    lbs = val * 2.2046    templateData = {'data' : lbs}    return jsonify(templateData), 200if __name__ == "__main__":    app.run(host='0.0.0.0', port=80, debug=True)

Modify the JavaScript accordingly to send the request to the new route /update, as I have not used the jQuery for ages, so I used my own pure JavaScript here:

<!DOCTYPE html><html lang="en"><head>    <meta charset="utf-8">    <title>Flask App</title></head><body>  <div id='test'></div><script>  document.addEventListener("DOMContentLoaded", function(event) {    const getSensorReading = function() {      fetch(`http://${location.host}/update`)  // send request to route /update        .then((resp) => resp.json())        .then(function(response) {          document.getElementById('test').innerHTML =response.data.toFixed(2);      });    }    getSensorReading();    setInterval(getSensorReading, 1000);  //request for update every 1 second  });</script></body></html>

Please test the code yourself as I did not test the code. This is mostly copy-and-pasted from my project which offers more sophisticated usage cases on sensor reading and web development that you might find beneficial.