Flask Restless JSON 格式化十进制

duf*_*ffn 5 python json flask-restless

我正在使用 Flask-Restless 0.17 作为 API。API 有几个小数字段。我可以通过安装 simplejson 成功返回小数,如下所述: https: //stackoverflow.com/a/15224186/1753891

但是,当我的小数字段为 0 时,该值采用科学记数法,例如0E-8。我想转而返回0.00000000

我正在尝试类似的事情,但无法让它发挥作用。0 仍然以科学记数法返回。

class DecimalJSONEncoder(json.JSONEncoder):
    # Try to format the decimal
    # EDIT: but am now realizing that this doesn't work
    # It was serializing the decimal at all because I had 
    # simplejson installed.
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return format(str(o), '.8f')
        return super(DecimalJSONEncoder, self).default(o)


def init_app(app):
    # .....
    # Use the Flask-Restless postprocessor to format.
    def postprocesor(result, **kw):
        json.dumps(result, cls=DecimalJSONEncoder)
Run Code Online (Sandbox Code Playgroud)

如何强制小数为零0.00000000