【发布时间】:2016-12-09 11:59:52
【问题描述】:
我想通过 Raspberry Pi 直播一些数据,例如我家的温度。我可以收集数据,但如何在不刷新的情况下更新页面?我听说过 AJAX 和 JavaScript,但我不知道如何将它与 Flask 一起使用。
from flask import Flask, request, make_response, abort, redirect, render_template, jsonify
app = Flask(__name__)
tempc = 0.0
temp_sensor = "/sys/bus/w1/devices/28-000007013b3f/w1_slave"
def temp_raw():
f = open(temp_sensor, "r")
lines = f.readlines()
f.close()
return lines
def read_tempc():
lines = temp_raw()
temp = lines[1].strip()[-5:]
tempc = float(temp)/1000
tempc = round(tempc, 1)
return tempc
@app.route('/temp', methods = ['GET'])
def temp():
temp = read_tempc()
return render_template('temp.html', temp=temp)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>"Test Temperature</title>
</head>
<body>
<h1> Je suis ici </h1>
<p> La température de la pièce est de: {{ temp }}°.</p>
<script text = "text/javascript">
function() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT+"/temp",
function(data) {
$("#getTemp").text(data.temp+"°")
});
};
</script>
</body>
</html>
编辑:我已经看到了这个解决方案enter link description here
但我不明白我必须把 Js 代码放在哪里,而且如果我使用这个解决方案,jsonify(temp=temp) 只会在页面上打印:`
{
"temp": 31.2
}
所以我只是想要一些解释,提前谢谢,晚上好:p
【问题讨论】: