![](/img/trans.png)
[英]Python Flask: How to easily consume dozens of HTML form fields and use them in a DB call?
[英]iterating thru fields in html form and passing them to function in python with flask
我有以下 html 和 n 组输入:
<form action="{{ url_for('list_names') }}" method="POST">
<label>Name</label>
<input name="peson_name" type="text">
<label>Age</label>
<input name="person_age" type="number">
<label>Name</label>
<input name="peson_name" type="text">
<label>Age</label>
<input name="person_age" type="number">
</form>
我想遍历每个输入并将它们传递给 python function 使用 flask 并创建字典列表
@app.route('/list_names', methods=["GET", "POST"])
def list_names():
if request.method == 'POST':
这就是我坚持的地方。 我正在寻找的 output 是一个字典列表,理想情况下应该如下所示:
[
{
'name': 'person1',
'age': 25
},
{
'name': 'person2',
'age': 30
}
]
使用request.form.getlist(...)
可以查询具有指定名称的输入字段中的所有值。 可以使用zip
组合通过这种方式获得的姓名和年龄列表。 因此,对是由具有相同索引的值组成的。 然后只需要从接收到的元组中形成一个字典。
from flask import (
Flask,
render_template,
request
)
app = Flask(__name__)
@app.route('/list_names', methods=['GET', 'POST'])
def list_names():
if request.method == 'POST':
names = request.form.getlist('person_name')
ages = request.form.getlist('person_age', type=int)
data = [{ 'name': name, 'age': age } for name,age in zip(names, ages)]
print(data)
return render_template('list_names.html')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.