使用flask更新web应用程序中的变量



我有一个arduino程序和设置,它可以检测停车场的汽车数量。每当传感器检测到障碍物前方有汽车时,汽车数量就会打印在序列号上。我想把停车场的汽车数量打印到一个小的网络应用程序中。我使用Tera Term扫描我的串行总线,并将输出数据放入一个文件文本(data.txt(中。然后我使用python读取该文本文件中的值,并将其呈现到web应用程序上的HTML页面中。

以下是python代码:

from flask import Flask, render_template
import logging
import requests

# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
@app.route("/")
def form():
with open('date.txt') as f:
data = []
lines = f.read().splitlines()
data.append(lines)
for i in data:
return render_template('index.html', variable=data)

if __name__ == "__main__":
app.run()

这是index.html

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Arduino Project</title>
<style>
body{
background: antiquewhite;
}
h1 {color:red;
text-align: center;}
h2 {color:blue;
text-align: center;}
</style>
</head>
<body>
<h1> - Arduino - </h1>
<h2> Number of cars in the parking place: {{ variable }}<br></h2>
<script> setTimeout(function(){
window.location.reload(1);
}, 5000);
</script>
</body>
</html>

它运行良好,但我希望只有一个变量,当页面刷新时,每5秒更新一次。我不想看到date.txt中的所有值,只想看到最后一个值。

这就是我的web应用程序到目前为止使用此代码的样子:(忽略错误消息(在此处输入图像描述

不可能多次返回。

返回语句用于结束函数调用的执行并"返回"结果(返回后的表达式的值关键字(。return语句之后的语句是未执行。

所以这个部分可以调整:

for i in data:
return render_template('index.html', variable=data)

你说你只想要最后一行。因此,将上面的内容替换为:

return render_template('index.html', variable=data[-1])

文档

获取列表的最后一个元素

https://www.geeksforgeeks.org/python-return-statement/

最新更新