【问题标题】:Why is my form deserialized as Mutlidict with strings instead of integers in flask [duplicate]为什么我的表单反序列化为 Mutlidict 字符串而不是烧瓶中的整数 [重复]
【发布时间】:2020-01-09 13:14:01
【问题描述】:

我从 html 页面发送表单,一些(但不是全部)输入似乎是字符串而不是整数。 此表单有 60 多个输入。

我可以在我的 dict 中手动将每个数字输入转换为 int,但我不知道要转换的所有输入名称。

我有一个烧瓶模板

<!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 此处问题的解决方案需要我事先知道哪个输入实际上是字符串或整数,事实并非如此

【问题讨论】:

    标签: python flask deserialization


    【解决方案1】:

    如果可能,您可以遍历所有这些并转换为int

    for key, val in select.items():
        try:
            select[key] = int(val)
        except ValueError:
            pass
    

    【讨论】:

    • 我已经编辑了这个问题:我不知道哪个应该是 int 哪个应该是 string
    • 根据我的回答,任何可以转换为int 的东西都可以。其他一切都将保持原样。除此之外,按照原样,没有什么可以做的。
    • 好的,我试试看
    • 很好,成功了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2018-06-08
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多