Flask-Restless转储Flask-Sqlalchemy的十进制值 [英] Flask-Restless dumps Decimal value from Flask-Sqlalchemy

查看:475
本文介绍了Flask-Restless转储Flask-Sqlalchemy的十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 类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。问题是当我从HTTP API的HTTP GET:

 文件/usr/lib/python2.6/json/encoder 
TypeError:Decimal('10000.0000000000')不是JSON可序列化

问题很明显,JSON编码器不能编码映射到价格(数字列类型)的十进制值。使用自定义JSON编码器启用Flask-Restless是否有任何解决方法?解答方案

下面是我所做的:$ / $> $ / $>

  import simplejson as json 

def postprocessor(data):
json.dumps(data,use_decimal = True )
返回数据

manager.create_api(Menu,methods = ['GET','POST','PATCH'],allow_patch_many = True,postprocessors = {
'PATCH_MANY ':[postprocessor],
'GET_MANY':[postprocessor],
'POST':[postprocessor]
})
p>

编辑:实际上,安装simplejson似乎已经足够了。您的代码无需更改。


i have this model using 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)

and i can create api using Flask-Restless for this model. The problem is when i HTTP GET from the api url:

  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

The problem is obvious the JSON encoder cannot encode Decimal value which is mapped to price (Numeric column type). Is there any workaound to enable Flask-Restless using custom JSON encoder?

解决方案

Here is what I did:

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]
})

So the idea is to use Flask-Restless' postprocessor to encode the data with simplejson instead of json since simplejson supports the Decimal() type by specifying use_decimal=True.

Edit: Actually it seems like installing simplejson might be sufficient. No change needed in your code.

这篇关于Flask-Restless转储Flask-Sqlalchemy的十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆