尝试使用Flask和jquery将python中的实时传感器数据转换为html,而不刷新整个页面

2024-06-16 12:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用树莓pi从负载传感器读取数据。我可以成功地从python文件中获取数据,但当我尝试使用flask将其传递到html文件时,它无法正确更新数据。它的行为就像不获取当前数据,只是反复加载相同的数据

*请参阅底部以了解更新

这是我的main.py文件-

#! /usr/bin/python3
import time
import sys
from flask import Flask, render_template
import datetime
app = Flask(__name__)

@app.route("/main")
def main():  
    EMULATE_HX711=False
    referenceUnit = 1

    if not EMULATE_HX711:
        import RPi.GPIO as GPIO
        from hx711 import HX711
    else:
        from emulated_hx711 import HX711

    hx = 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 is the only data I would like to refresh and stream into html
    while True:
        try:
            val = hx.get_weight(5)
            lbs = val * 2.2046
            templateData = {
                'data' : lbs
                }
            return render_template('index.html', **templateData)
                 
            hx.power_down()
            hx.power_up()
            time.sleep(1)

        except (KeyboardInterrupt, SystemExit):
            cleanAndExit()

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80, debug=True)

我正在尝试将lbs作为数据传递到index.html-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Flask App</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>

<div id='test'></div>

<script>
function loadlink(){

    $('#test').load('/main',function () {
        $(this).unwrap();
        $('#test').replaceWith('{{ data }}');
    });
}

loadlink();
setInterval(function(){
    loadlink()
}, 1000);
 
 </script>

 </body>
 </html>

更新 我发现每次刷新都会重置数据,因为-

hx.reset()
hx.tare()

这是需要在零开始传感器,但一旦开始,我希望它流传感器数据,因为它的变化。我如何在不刷新页面的情况下完成此操作


Tags: 文件数据fromimportappflaskdatamain
1条回答
网友
1楼 · 发布于 2024-06-16 12:20:29

python代码在收到来自浏览器的每个请求时返回index.html的整个页面,您应该做的不是return render_template('index.html', **templateData),而是只返回类似return jsonify(templateData), 200的数据。为此,创建一个单独的路由来处理请求

#! /usr/bin/python3
from flask import Flask, render_template, jsonify

app = Flask(__name__)
EMULATE_HX711=False
referenceUnit = 1

if not EMULATE_HX711:
   import RPi.GPIO as GPIO
   from hx711 import HX711
else:
   from emulated_hx711 import HX711

hx = 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), 200


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80, debug=True)

相应地修改JavaScript以将请求发送到新路由/update,因为我已经很久没有使用jQuery了,所以我在这里使用了我自己的纯JavaScript:

<!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>

请自己测试代码,因为我没有测试代码。这主要是从my project复制和粘贴的,my project提供了关于传感器读取和web开发的更复杂的用例,您可能会发现这些用例是有益的

相关问题 更多 >