繁体   English   中英

flask-我无法显示第二个app.route的输出

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM