【发布时间】:2021-06-18 13:14:36
【问题描述】:
我想在我的烧瓶 webapp 中启用/禁用 IoT 设备的自动驾驶功能。 该开关似乎仅在从 OFF 位置移动到 ON 位置时才起作用。
如果您尝试将其从 ON 切换到 OFF,它只会重新加载页面并将开关保持在 ON 位置。
这是我使用的代码
在 HTML 模板中我循环遍历所有设备以通过开关显示它们的 Autopilot 状态。单击时,表格将被发布。这是一段简化的代码。
{% for device in devices %}
<form method="POST">
<div class="form-check form-switch">
<label class="form-check-label" for="{{device.unique_id}}.autopilot">Autopilot</label>
<input class="form-check-input" type="checkbox" name="{{device.unique_id}}.autopilot" {% if device.autopilot %}checked{% endif %} onclick="submit();">
{% endfor %}
Here is an example of what the switch looks like
在烧瓶 app.py 中我有一个设备列表,当发送 POST 请求时,它会遍历设备列表以检查要打开或关闭哪个自动驾驶仪。
@app.route('/', methods=['GET', 'POST'])
def home():
global devices
if request.method == "POST":
# decode response & filter out the unique ID
response = request.get_data().decode("utf-8")
resp_device_id = response.split(".")[0]
# compare unique ID with devices & toggle autopilot
for d in devices:
if str(d.unique_id) == resp_device_id:
d.autopilot = not d.autopilot
else:
print(str(d.unique_id) + "&" + resp_device_id + "do not match")
return render_template('home.html', devices = devices)
从关闭切换到开启时一切正常。但是从 ON 切换到 OFF 时,POST 响应似乎是空的。所以 IF 语句的结果是 FALSE 并且没有任何东西被切换。
有什么想法可以在这里出错吗?
【问题讨论】:
-
你使用Javascript吗?您是否检查过 JavaScript 控制台中是否出现错误?也许它会引发错误,然后它不会停止重新加载它。
-
未选中时您期望的值是多少?正如我所记得的,当输入未选中时,它不会发送值,这样您就可以识别出它未选中。因此,首先您应该在
False上设置所有值,然后代码将为您从浏览器获得的所有复选框设置True。 -
感谢@furas 您的评论让我找到了答案。未选中时不会发送任何值。
标签: python user-interface flask request http-post