Python 重新加载页面重新发送数据

Python 重新加载页面重新发送数据,python,flask,Python,Flask,我有一个带有Flask的简单代码。我有一个网站,有4个按钮,当按下按钮时,会将帖子发送到烧瓶,并返回相同的页面,但按钮会以另一种颜色拧紧。每个按钮的状态存储在布尔数组中。 这是烧瓶代码: import numpy as np from flask import Flask, request, render_template app = Flask(__name__) states = np.array([0, 0, 0, 0], dtype=bool) @app.route('/contro

我有一个带有
Flask
的简单代码。我有一个网站,有4个按钮,当按下按钮时,会将帖子发送到
烧瓶
,并返回相同的页面,但按钮会以另一种颜色拧紧。每个按钮的状态存储在布尔数组中。
这是
烧瓶
代码:

import numpy as np
from flask import Flask, request, render_template

app = Flask(__name__)
states = np.array([0, 0, 0, 0], dtype=bool)

@app.route('/control', methods=['GET', 'POST'])
def control():
    if request.method == 'POST':
        val = int(request.form['change rele state'])
        states[val] = not states[val]

        return render_template('zapa.html', states=states)
    else:
        return render_template('zapa.html', states=states)

if __name__ == '__main__':
    app.run(debug=True)
以及网页:

{% extends "layout.html" %}

{% block content %}
  <h2>Control</h2>
  <p>Botones</p>

  <p>{{ states }}</p>

  <form action="/control" method="POST">
    {% for state in states %}
      {% if state == True %}
        <button class="btn btn-primary" type="submit" name="change rele state" value="{{ loop.index0 }}">Enchufe {{ loop.index }} Off</button>
      {% endif %}
      {% if state == False %}
        <button class="btn btn-danger" type="submit" name="change rele state" value="{{ loop.index0 }}">Enchufe {{ loop.index }} On</button>
      {% endif %}
    {% endfor %}
  </form>

{% endblock %}
{%extends“layout.html”%}
{%block content%}
控制
鲍通

{{states}}

{状态为%的状态为%} {%if state==True%} Enchufe{{loop.index}}关闭 {%endif%} {%if state==False%} Enchufe{{loop.index}}On {%endif%} {%endfor%} {%endblock%}

问题是,当按下重新加载页面时,发送就像按下按钮一样。为什么?我怎样才能避免这种情况呢?

我对flask没有深刻的理解,事实上根本没有,但在我看来,你已经让你的服务器记住了你所说的这个按钮的状态

return render_template('zapa.html', states=states)
您不是返回更改后的原始状态,而是使用“更改角色状态”请求返回帖子上先前状态的更改版本,否则保留原始值

我想你想做的是(如果我错了,请纠正我如下)

这将创建状态的副本,而不是在全局范围内对其进行更改,以便下次调用控件时,状态列表将处于其原始状态

从我的角度来说,这可以更优雅地编码,但我只是想说明一下这个问题

@app.route('/control', methods=['GET', 'POST'])
def control():
    if request.method == 'POST':
        val = int(request.form['change rele state'])
        current_states = states[:]
        current_states[val] = not current_states[val]
        return render_template('zapa.html', states=current_states)
    else:
        return render_template('zapa.html', states=states)