簡體   English   中英

嘗試使用 Flask 和 ZD223E1439188E469883A822C7A53EZ 將實時傳感器數據從 python 獲取到 html 而不刷新整個頁面

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

我正在嘗試使用樹莓派從負載傳感器讀取數據。 我可以成功地從 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()

這需要在零處啟動傳感器,但是一旦啟動,我希望它在傳感器數據發生變化時對 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 進行更改。 如果不刷新頁面,我怎么能做到這一點?

您的 python 代碼返回 index.html 的整個頁面在收到來自瀏覽器的每個請求時,您應該做的不是return render_template('index.html', **templateData) ,而是返回類似return jsonify(templateData), 200的數據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>

請自己測試代碼,因為我沒有測試代碼。 這主要是從我的項目中復制和粘貼的,該項目提供了關於傳感器讀取和 web 開發的更復雜的使用案例,您可能會發現這些案例很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM