为什么“类型为Decimal的对象不可JSON序列化"? -在将棉花糖与SQLAlchemy自动映射一起使用时? [英] Why is "Object of type Decimal is not JSON serializable" - when using marshmallow with SQLAlchemy automap?

查看:303
本文介绍了为什么“类型为Decimal的对象不可JSON序列化"? -在将棉花糖与SQLAlchemy自动映射一起使用时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用sqlalchemy.ext.automap中的automap_base映射我的表. 无法shema.dumps(result);

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

获取

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

尝试使用JSON自定义解码器,但没有用.

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)

推荐答案

JSONtransform一个SQLAlchemy result对象的简单解决方法是使用simplejson.

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

您只需要导入它(import simplejson)即可.

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

使用您的示例:

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

这篇关于为什么“类型为Decimal的对象不可JSON序列化"? -在将棉花糖与SQLAlchemy自动映射一起使用时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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