2015-11-29 77 views
0

我有一个简单的代码Flask。我有一个网站有4个按钮,当按下后发送POST到Flask并返回相同的页面,但用另一种颜色收紧的按钮。每个按钮的状态都存储在布尔数组中。
这是Flask代码:重新加载页面重新发送数据

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 %} 

的问题是,按重新加载页面,仿佛按下按钮时发送。为什么?我如何避免这种情况?

回答

0

我对烧瓶的理解并不深刻,但对我来说,似乎你已经让你的服务器记住了你正在谈论的这个按钮的状态。

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

而不是返回一个改变状态,您传回以前状态对POST改编版与“变化中的作用状态的要求,并保持原来的值,否则。

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

@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) 

这导致各州的副本,而不是改变它在全球范围内,是什么使下一次控制被调用时,状态列表将处于其原始状态

这可以在我的身边更优雅地编码,但我只是试图说明问题。

相关问题