简体   繁体   English

防止Flask + jinja2将长整数转换为十进制

[英]Prevent Flask + jinja2 from converting a long integer into a decimal

[a total python noob] [一个总的Python菜鸟]
I'm rendering a template and passing in a dictionary: 我正在渲染模板并传递字典:

d = {'id':3423444989845}

but when I'm doing like so <div id="{{d['id']}}"> instead of getting <div id="3423444989845"> the HTML renders like this: <div id="3.423445e+12"> . 但是当我这样做时<div id="{{d['id']}}">而不是得到<div id="3423444989845"> HTML呈现如下: <div id="3.423445e+12">

How can I prevent this? 我该如何预防? (my temporary solution was to pass the id as a string, but I was hoping to keep it an integer. (我的临时解决方案是将id作为字符串传递,但我希望将其保留为整数。

Thanks 谢谢

The issue is that your ID is a float, not an integer (JavaScript's Date#getTime returns a float and I'm willing to wager that MongoDB is also storing the value as a float.) If you want it to be treated as an integer you should convert the value you are given by JavaScript to an integer in your Python code: 问题是您的ID是浮点数,而不是整数(JavaScript的Date#getTime返回一个浮点数,我敢打赌MongoDB还将值存储为浮点数。)如果希望将其视为整数您应该将JavaScript给定的值转换为Python代码中的整数:

if request.method == "POST":
    try:
        # Remember, *never* trust user input
        # This is most likely a number but you are not guaranteed that
        data_id = int(request["id"])
    except ValueError:
        abort(400)
    # If we got here, we have a valid int
    # Insert data into MongoDB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM