首页 > 解决方案 > 使用按钮操作后如何在 Flask 中处理表单参数

问题描述

我很难用 Flask 和 python 弄清楚以下内容:

这部分会导致以下情况

http://localhost/ENA/on

@app.route("/<deviceName>/<action>")
def action(deviceName, action):
**// CODE // **
templateData = {
        'ENA'  : enaSts,
        'SWITCH'  : switchSts,
        'DIR': dirSts,
        'FREQ' : freq}     

return render_template('index.html', **templateData)  

接下来将导致以下情况:

http://localhost/ENA/setFreq

但想要的结果是:

http://localhost/setFreq

@app.route ("/setFreq", methods =["POST"] )
def setFreq():
    global freq
    **// CODE // **

    templateData = {
            'FREQ'  : freq,          
    }
        
    return render_template('index.html', **templateData)

到目前为止尝试了什么:

@app.route("/<deviceName>/<action>")
def action(deviceName, action):
**// CODE //**
return redirect(request.path)

这会导致

重定向你太多次。

提交表单时,需要刷新页面以显示新提交的值 {{FREQ}} 与 python 一起使用

<form method="POST" action="setFreq"> 
        <label for="freq">freq:{{FREQ}}</label><br>
        <input type="text" id="freq" name="freq"><br>
        <input type="submit" value="Submit">
    </form>

注意:如果setFreq在使用前从索引提交

/<deviceName>/<action>

FREQ 将按要求提交

http://localhost/setFreq

HTML 代码供参考:

  <h3> ENA ==>  {{ ENA  }}  ==>   
        {% if  ENA   == 1 %} 
            <a href="/ENA/off"class="button">TURN OFF</a> 
        {% else %} 
            <a href="/ENA/on" class="button">TURN ON</a>  
        {% endif %}      
    </h3> 
    <h3> DIR ==>  {{ DIR  }}  ==>   
        {% if  DIR   == 1 %} 
            <a href="/DIR/off"class="button">TURN OFF</a> 
        {% else %} 
            <a href="/DIR/on" class="button">TURN ON</a>  
        {% endif %}      
    </h3> 


    <form method="POST" action="setFreq"> 
        <label for="freq">freq:{{FREQ}}</label><br>
        <input type="text" id="freq" name="freq"><br>
        <input type="submit" value="Submit">
    </form>

标签: pythonflask

解决方案


推荐阅读