【问题标题】:how to get and post data in a Flask Dropdown menu如何在 Flask 下拉菜单中获取和发布数据
【发布时间】:2020-08-05 21:44:15
【问题描述】:

我正在使用烧瓶,我正在努力从下拉菜单中获取数据,我在下拉菜单中从列表“Mydevices”中列出值,因为我使用 Get 方法,我知道我不能同时使用 Get 和 Post 方法,那么当使用选择设备时,如何让我的 Device 变量提交回来?也许使用java脚本?是否有另一种无需编写 java 脚本代码即可获取数据的方法?

<form id="form" action="" method="POST">
<div class="container">
    <div class="row">
    <a class='dropdown-button btn' href='#' data-activates='dropdown1' data-beloworigin="true">Select Device  <img src="/static/pictures/down-arrow.png"></a>
        <ul id='dropdown1' class='dropdown-content'>
          <li><a name="device" method="GET" SelectDevice="/">
            <li><a inputmode="submit" value="{{mydevices[0]}}" selected>{{mydevices[0]}}</a></li>

             {% for device in mydevices[1:] %}

              <li><a value="{{device}}">{{device}}</a></li>
              {% endfor %}
<!--  </li></a> -->
  </ul>

</div>

</div>

 <div class="container">
    <div class="row">
         <div class="col-md-4 col-sm-4 col-xs-12 form-group">
              <label class="labeltext">filter Data by:</label><br>
                  <div class="form-check-inline">

                    <label class="customradio"><span class="radiotextsty">Days</span>
                      <input type="radio" checked="checked" name="radio" value="Days">
                      <span class="checkmark"></span>
                    </label>
                    <label class="customradio"><span class="radiotextsty">Months</span>
                      <input type="radio" name="radio" value="Months">
                      <span class="checkmark"></span>
                    </label>
                    <label class="customradio"><span class="radiotextsty">Seasons</span>
                      <input type="radio" name="radio" value="Seasons">
                      <span class="checkmark"></span>
                    </label>

                </div>
         </div>


    <div class="row">
        <button action= {{url_for('index')}} class="col s2 offset-s5 waves-effect waves-light btn" id="sub" type="submit" >Reset</button>
    </div></div>
          </div>
    </div>

</form>

这是我的python代码

@app.route('/device_statistics', methods=['POST', 'GET'])
def device_stats():

mydevices = ['Hall', 'Door101', 'Door102', 'Garage' , 'Fiat 500','Audi A3']

if request.method == 'POST':
       chosendevice = request.form['device']




return render_template('device_statistics.html', mydevices=mydevices, error=error)

....


这是我得到的错误:

werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'device'

【问题讨论】:

    标签: javascript python html flask get


    【解决方案1】:

    一个列表元素:

    <ul>
      <li></li>
      <li></li>
    </ul>
    

    不是&lt;form&gt; 元素的input。因此:

    chosendevice = request.form['device']
    

    给出一个关键错误,因为device 不在表单中。我认为你想要的是一个 &lt;select&gt; 元素,它是表单的一部分。或者,您可以将单击处理程序附加到您的列表中,但这有点高级。我认为这就是您尝试使用 &lt;a&gt; 标签所做的事情,但这不是正确的做法。

    请参阅:https://wtforms.readthedocs.io/en/2.3.x/fields/#basic-fields 以使用 SelectField

    试试:

    chosendevice = request.form.get('device', 'not in form')
    
    print(chosendevice)
    

    你会发现它不存在。

    【讨论】:

    • 确实,当我尝试您的代码时,结果发现它不在表单中,但我不知道如何继续,我不能听我的 a 标签吗?或者我是否必须更改我使用的组件?
    【解决方案2】:

    我认为你想要异步数据,所以需要使用 javascript。如果你跟着我 -

    您的 html 的修改部分 -

    <ul id='dropdown1' class='dropdown-content'>
       <li><a name="device" method="GET" SelectDevice="/">
    
       <!-- added an id (submitButton) to call function in javascript -->  
       <li><a id="submitButton" inputmode="submit" value="{{mydevices[0]}}" selected>{{mydevices[0]}}</a></li>
     
       
    
    </ul>
    

    使用javascript fetch api向flask发送post请求:

    const button = document.getElementById('submitButton');
    
    button.onClick = function(){
    
      chosendevice = // its your responsibility to bring the device name here as string
    
      fetch(`${window.origin}/device_statistics`, {
         method: "POST",
         credentials: "include",
         cache: "no-cache",
         body: chosendevice,
    
      }).then(res => {
          // here response comes (not your question primarily)
    
         if(res.status !== 200) return;
    
         res.text().then(data => 
    
          // do whatever 
    
         });
    
      }).catch(e => {
         console.log(e);
      });
    
    }
    

    你的烧瓶后端:

    @app.route('/device_statistics', methods=['POST', 'GET'])
        def device_stats():
    
            mydevices = ['Hall', 'Door101', 'Door102', 'Garage' , 'Fiat 500','Audi A3']
    
            if request.method == 'POST':
               chosendevice = request.get_data().decode('utf-8')
               print(chosendevice)
    
               # do whatever with chosendevice          
    
               return 'whatever'
    
        return render_template('device_statistics.html', mydevices=mydevices, error=error)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-05
      • 2015-03-02
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      相关资源
      最近更新 更多