Why is “Object of type Decimal is not JSON serializable” - when using marshmallow with SQLAlchemy automap?

社会主义新天地 提交于 2020-01-03 01:40:08

问题


Using automap_base from sqlalchemy.ext.automap to map my tables. Not able to shema.dumps(result);

getting

raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

Tried using JSON custom decoders, but no use.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
from flask_marshmallow import Marshmallow

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

db = SQLAlchemy(app)
ma = Marshmallow(app)

engine = db.engine
session = Session(engine)

Base = automap_base()
Base.prepare(engine, reflect=True)

MyTable = Base.classes.my_table

class MyTableSchema(ma.ModelSchema):
    class Meta:
        model = MyTable

@app.route("/")
def api():
    all_rows = session.query(MyTable).all()
    schema = MyTableSchema(many=True)
    response = schema.dumps(all_rows)

    return response

if __name__ == '__main__':
    app.run(debug=True)


回答1:


An easy workaround to transform an SQLAlchemy result object in JSON is using simplejson.

You just need to import it (import simplejson) and it works.

Using your example:

import simplejson
...
@app.route("/")
def api():
    all_rows = session.query(MyTable).all()
    response = simplejson.dumps(all_rows)


来源:https://stackoverflow.com/questions/56559808/why-is-object-of-type-decimal-is-not-json-serializable-when-using-marshmallo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!