Flask-Restless 导出 Flask-Sqlalchemy 的 Decimal 值
我有一个使用 Flask-SQLAlchemy 的模型:
class Menu(Document, db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(80), unique=True, index=True)
price = db.Column(db.Numeric)
我可以用 Flask-Restless 为这个模型创建 API。不过,当我从 API 的网址进行 HTTP GET 请求时:
File "/usr/lib/python2.6/json/encoder.py", line 344, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Decimal('10000.0000000000') is not JSON serializable
问题就出现了,明显是 JSON 编码器无法处理与价格相关的 Decimal 值(这是一个数字类型的列)。有没有什么办法可以让 Flask-Restless 使用自定义的 JSON 编码器呢?
2 个回答
4
正如mickael的回答所提到的,安装simpejson就足够了。另外,后处理器的正确语法如下:
#first argument must be named as 'result', not 'data'
def postprocessor(result):
json.dumps(result, use_decimal=True)
#return data - postprocessors/preprocessors should not return values!
5
我做了以下事情:
import simplejson as json
def postprocessor(data):
json.dumps(data, use_decimal=True)
return data
manager.create_api(Menu, methods=['GET', 'POST', 'PATCH'], allow_patch_many=True, postprocessors={
'PATCH_MANY': [postprocessor],
'GET_MANY': [postprocessor],
'POST': [postprocessor]
})
我的想法是使用Flask-Restless的后处理器,用simplejson来编码数据,而不是用json,因为simplejson支持Decimal()类型,只需要设置use_decimal=True。
补充:实际上,安装simplejson可能就够了。你的代码不需要做任何更改。