我正在从 html 页面发送表单,一些(但不是全部)输入似乎是字符串而不是整数。 此表单有 60 多个输入。
我可以手动将每个数字输入转换为字典中的 int,但我不知道要转换的所有输入名称。
我有一个 flask 模板
<!doctype html>
<form class="form-inline" method="POST" action="{{ url_for('result') }}">
<div>
<p>nb_ref</p>
<input type="number" name="nb_ref" value=1>
</div>
<div>
<p>type_client</p>
<input type="text" name="type_client" value="P">
</div>
...more inputs removed for clarity
<button type="submit" class="btn">Go</button>
</form>
我在这里输出响应
@app.route("/result", methods=['GET', 'POST'])
def result():
error = None
select = request.form.to_dict()
pp(select)
这在我的日志中给出了我
{'SST_si_second_devis': '0',
...more items removed for clarity
'nb_ref': '1',
'type_client': 'P'}
我希望有一个输出的字典,如下所示
{'SST_si_second_devis': 0,
...more items removed for clarity
'nb_ref': 1,
'type_client': 'P'}
编辑:
问题的解答在这里Cast Flask form value to int需要我事先知道哪个输入实际上是字符串或整数,但事实并非如此
最佳答案
如果可能的话,您可以循环所有这些并转换为 int
。
for key, val in select.items():
try:
select[key] = int(val)
except ValueError:
pass
关于python - 为什么我的表单在 Flask 中被反序列化为带有字符串而不是整数的 Mutlidict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57825732/