[英]flask - I can't get to show the output of the second app.route
我有這個用於顯示溫度和距離的python代碼(使用傳感器)。 顯示了溫度值,但沒有顯示距離值。 編碼有什么問題?
我似乎無法解決該怎么做。 我嘗試將傳感器數據輸出保存到文本文件dis.txt,但仍無法正常工作。
謝謝您的幫助。
網絡快照: websnapshot
蟒蛇:
from flask import Flask, render_template
import RPi.GPIO as GPIO
import datetime
import os
#from flask import jsonify
import time
import glob
import sonic
import subprocess
from time import strftime
app = Flask(__name__)
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
os.system('sudo python /home/pi/webserver/sonic.py | tee /home/pi/dis.txt')
temp_sensor='/sys/bus/w1/devices/28-0416a2aca1ff/w1_slave'
dista='/home/pi/dis.txt'
@app.route("/")
def tempReading():
t=open(temp_sensor,'r')
lines=t.readlines()
t.close()
temp_output = lines[1].find('t=')
if temp_output != -1:
temp_string=lines[1].strip()[temp_output+2:]
temp_c=float(temp_string)/1000.0
templateData = {
'temp': round(temp_c,1)
}
#return jsonify(temp_c)
return render_template('temp.html',**templateData)
@app.route("/")
def distance():
t=open(dista,'r')
lines=t.readlines()
t.close()
distance_output = lines[1].find('Distance: ')
templateData = {
'dis': distance
}
return render_template('temp.html',**templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
temp.html:
<!DOCTYPE html>
<html>
<head>
<!--Pescuela, Galilea-->
<title>Water Quality Monitor</title>
<meta http-equiv="refresh" content="2"
</head>
<body>
<center>
<font face="Helvetica" size="30">Temperature</font>
<br><br><strong><font face="Helvetica" size="100">{{ temp }} °C</font></strong>
<br>
<font face="Helvetica" size="30">Water level</font>
<br><br><strong><font face="Helvetica" size="100">{{ dis }} cm</font></strong>
</body>
</html>
您已經用基本路由"/"
裝飾了這兩個函數。 就目前而言,這意味着Flask僅在您到達URL的基本路徑時才會運行第一個功能。
如果要將distance()
保留為單獨的函數,請刪除@app.route
裝飾器,對其進行修改以返回要在頁面上顯示的值,然后從tempReading()
函數中調用此函數,並添加返回值到templateData
字典。
感謝您的回答。
我雖然找到了一種從函數內部執行python腳本的方法。 我剛剛添加了dista=subprocess.check_output('sudo python /home/pi/webserver/sonic.py', shell=True)
,它獲取腳本的輸出並保存到變量dista
,然后將其添加到templateData
字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.