将参数从网页传递到服务器(烧瓶)

Passing parameters from webpage to server (Flask)

本文关键字:服务器 烧瓶 参数 网页      更新时间:2023-09-26

我刚刚开始在我的前端代码中添加后端,并认为 flask 是一个很好的开始学习的框架。

我遇到麻烦的一件事是将信息提交到服务器进行处理。具体来说,这里有一个单选按钮列表,我想向服务器发送用户点击提交时选中的所有单选按钮的列表。然后,服务器处理该信息并返回一个新页面。

这是形式:

<form action="{{ url_for('timeline') }}" method="post">
   {% for each_tag in tags %}
  <div class="checkbox">
      <label>
        <input type="checkbox" name="channel[]" value="{{each}}" >
        {{each_tag}} 
      </label>
  </div>    
{% endfor %} 
   <button type="submit"> submit </button>
</form>

以下是主烧瓶文件中的相关功能:

@app.route('/')
@app.route('/index.html')
def checklist():
    for rownum in range(1,sh.nrows):
        row_values = sh.row_values(rownum)
        all_tags.add(row_values[7])
    return render_template('index.html', tags=all_tags)
@app.route('/timeline.html', methods=['POST','GET'])
def timeline(request):
    //do stuff with list of checked radio buttons
    return render_template('timeline.html')

我不确定信息是如何来回传递的。我可以将服务器信息发送到 html 模板,我认为一旦我记下这个示例并弄清楚信息是如何向另一个方向传递的,我就可以开始做一些有趣的事情了。=)

用尾随方括号("channel[]")命名复选框是PHP的事情,Flask不需要它。

只需在所有复选框中使用相同的名称:

<form action="{{ url_for('timeline') }}" method="post">
   {% for each_tag in tags %}
    <input type="checkbox" name="channel" value="{{each}}" >
   {% endfor %} 
    <button type="submit"> submit </button>
</form>

然后,要检索所选值的数组,请使用request.form.getlist()

@app.route('/timeline.html', methods=['POST','GET'])
def timeline(request):
    checked = request.form.getlist('channel')
    # do something with checked array
    return render_template('timeline.html')