遍历 html 形式的字段并将它们传递给 python 中的 flask 函数
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>
我想遍历每个输入并使用 flask 将它们传递给 python 函数并创建字典列表
@app.route('/list_names', methods=["GET", "POST"])
def list_names():
if request.method == 'POST':
这就是我卡住的地方。我正在寻找的输出是一个字典列表,理想情况下应该是这样的:
[
{
'name': 'person1',
'age': 25
},
{
'name': 'person2',
'age': 30
}
]
与request.form.getlist(...)
all values from input fields with the specified name can be queried. The lists of names and ages obtained in this way can be combined using 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')
我有以下 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>
我想遍历每个输入并使用 flask 将它们传递给 python 函数并创建字典列表
@app.route('/list_names', methods=["GET", "POST"])
def list_names():
if request.method == 'POST':
这就是我卡住的地方。我正在寻找的输出是一个字典列表,理想情况下应该是这样的:
[
{
'name': 'person1',
'age': 25
},
{
'name': 'person2',
'age': 30
}
]
与request.form.getlist(...)
all values from input fields with the specified name can be queried. The lists of names and ages obtained in this way can be combined using 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')