首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试使用Flask和jquery将python中的实时传感器数据转换为html,而无需刷新整个页面

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

Stack Overflow用户
提问于 2020-06-12 04:44:03
回答 1查看 1.8K关注 0票数 3

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

*请参阅底部更新

这是我的main.py文件-

代码语言:javascript
复制
#! /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中-

代码语言:javascript
复制
<!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>

更新我已经计算出每次刷新都会重置数据,因为-

代码语言:javascript
复制
hx.reset()
hx.tare()

这是从零开始启动传感器所需的,但一旦启动,我希望它在传感器数据发生变化时流式传输它。如何在不刷新页面的情况下完成此操作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-12 10:52:31

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

代码语言:javascript
复制
#! /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:

代码语言: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>

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62333250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档