尝试使用 Flask 和 jquery 将实时传感器数据从 python 获取到 html 中,而无需刷新整个页面



我正在尝试使用树莓派从负载传感器读取数据。我可以成功地从 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 作为数据传递到索引中.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()

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

你的python代码返回索引的整个页面.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>

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

最新更新