2015-11-29 74 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) 

這導致各州的副本,而不是改變它在全球範圍內,是什麼使下一次控制被調用時,狀態列表將處於其原始狀態

這可以在我的身邊更優雅地編碼,但我只是試圖說明問題。

相關問題