Post an array of objects from an HTML form using Flask?
本问题已经有最佳答案,请猛点这里访问。
我想从表单输入生成包含对象数组的JSON对象:
1 2 3 4 5 6 7 | { "network":[ {"layer_type":"conv2d","num_filters": 16,"kernel_size": 2,"padding":"valid","stride": 2}, {"layer_type":"max_pool2d","num_filters": 16,"kernel_size": 2,"padding":"valid","stride": 2}, {"layer_type":"conv2d","num_filters": 32,"kernel_size": 3,"padding":"valid","stride": 2} ] } |
有没有办法可以使用Flask做到这一点?
更新
这是表单的样子:
至于动态生成的html代码片段:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <li> <select name="network[][layer_type]"><!-- options here --></select> <input type="number" name="network[][num_filters]"> <!-- other parameters here --> </li> <li> <select name="network[][layer_type]"><!-- options here --></select> <input type="number" name="network[][num_filters]"> <!-- other parameters here --> </li> |
编辑:由于此问题被标记为重复,我将添加更多信息。 我想在这个问题中实现类似的东西但是使用Flask:
1 2 3 4 5 6 7 8 9 10 11 12 | {"students" => [ { "first" =>"foo", "last" =>"bar", "age" =>"21" }, { "first" =>"baz", "last" =>"qux", "age" =>"19" } ]} |
它根据已接受的答案与Ruby一起工作,具有以下形式:
1 2 3 4 5 6 7 8 9 | <!-- first student --> <input type="text" name="students[][first]"> <input type="text" name="students[][last]"> <input type="text" name="students[][age]"> <!-- second student --> <input type="text" name="students[][first]"> <input type="text" name="students[][last]"> <input type="text" name="students[][age]"> |
但我想知道如何使用Flask来做到这一点。
对于例如
考虑下面定义的表单,
1 2 3 4 | class GeneralForm(FlaskForm): boolean_val = BooleanField('Boolean') a_float = FloatField('Severity') submit = SubmitField('Submit') |
在应用程序路线中,
1 2 3 4 5 6 | @app.route('/wtforms', methods=['GET', 'POST']) def debug_wtforms(): form = GeneralForm() if request.method == 'POST' and form.validate_on_submit(): print(form.data) # Form data as a dict return render_template('index1.html', form=form) |
我希望这有帮助。