【问题标题】:update a variable in a web app with flask使用烧瓶更新 Web 应用程序中的变量
【发布时间】:2020-08-18 21:57:46
【问题描述】:

我有一个 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 中的所有值,只是最后一个。

到目前为止,这是我的网络应用程序在这段代码中的样子: (忽略错误信息) enter image description here

【问题讨论】:

    标签: python html flask server arduino


    【解决方案1】:

    不能多次返回。

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

    所以这部分可以调整:

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

    你说你只想要最后一行。所以用这个替换上面的:

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

    文档

    Getting the last element of a list

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

    【讨论】:

    • 试图替换它。我得到相同的输出。我认为问题出在 render_template() 函数上。它总是呈现相同的 html 页面并在旧页面旁边添加值。
    • 与以前相同的输出还是加载后始终相同?
    • 和以前一样。现在我有一个在 arduino 中运行的虚拟项目。它计数到 1000,每 5 秒打印一次索引。所以最终输出是 0, 1, 2, .... 1000,我将所有这些值打印到 Web 应用程序中。我只想要最后一个值。像 1,然后用 2 替换,然后用 3 替换,依此类推。
    • 我知道现在出了什么问题。您有一个包含 1 个值的列表。包含所有值的字符串。您应该将此字符串拆分为一个列表。然后只给出答案中给出的最后一个元素。
    • 完成,谢谢您的回答。这很有帮助。现在它完全按照我想要的方式工作:D
    猜你喜欢
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 2021-12-25
    • 2018-12-15
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    相关资源
    最近更新 更多