将变量从表单输入传递到烧瓶URL

时间:2016-12-07 21:07:30

标签: flask

我在Flask中有一个虚拟项目,它包含一个Web表单,您可以在其中填写3个城市,然后打印出来。 这是我的 init .py文件:

@app.route('/average_temperatures/<city1>/<city2>/<city3>', methods=['POST', 'GET'])
def results_temperature(city1, city2, city3):
    return "The cities are: {}, {}, {}".format(city1, city2, city3)

该函数有效,但我无法将表单中的变量直接传递给函数,作为参数。

修改

我的目标是将城市变量作为URL的一部分以干净的形式/ city1 / city2 / city3。

这是表格:

<div class="input-group">
<form action="{{ url_for('results_temperature', city1=city1, city2=city2, city3=city3) }}" method="POST">
  <input type="text" class="form-control" placeholder="City 1" name="city1"></input>
  <input type="text" class="form-control" placeholder="City 2" name="city2"></input>
  <input type="text" class="form-control" placeholder="City 3" name="city3"></input>
<div class="row" style="margin-bottom: 20px;"></div>

填写表单会产生一个网址

  

http://example.com/average_temperatures///

所以我显然无法传递表单操作部分中的表单字段。 任何点击都会受到赞赏,欢呼。

1 个答案:

答案 0 :(得分:0)

您应该从request.form变量中获取城市。

@app.route('/average_temperatures', methods=['POST', 'GET'])
def results_temperature():
return "The cities are: {}, {}, {}".format(request.form['city1'], request.form['city2'], request.form['city3'])

在您的HTML表单中:

<form action="{{ url_for('results_temperature') }}" method="POST">
    <input type="text" class="form-control" placeholder="City 1" name="city1"></input>
    <input type="text" class="form-control" placeholder="City 2" name="city2"></input>
    <input type="text" class="form-control" placeholder="City 3" name="city3"></input>
</form>
相关问题