不可 JSON 序列化 - Python + Flask + Sqlalchemy

Moh*_*eer 0 python mysql json sqlalchemy flask

我正在编写小查询以从mysql数据库中获取数据,我有一个报告表,在里面我有report_id,我需要查询匹配report_id来自apiparams的数据。

我的功能:

def view_single_thumbnail(idx): // idx coming from params 
    session = Session()

    result = session.query(
        Report
    ).filter(
        Report.report_id == idx
    ).all()

    return jsonify({
        'data': result
    })
Run Code Online (Sandbox Code Playgroud)

投掷错误:'components.db.core.table_declaration.Report object at 0x000001C1Fsdfsdf51E6A90' is not JSON serializable

Sam*_*ain 6

无法自动序列化 SQLAlchemy 对象jsonify。您可以向 SQLAlchemy 模型添加属性class

class Report(db.Model):
    def __init__(self):
        ...

    @property
    def serialized(self):
        """Return object data in serializeable format"""
        return {
            'id': self.id,
            'report_text': "Some text",
            ...
        }
Run Code Online (Sandbox Code Playgroud)

您的视图将更新为:

def view_single_thumbnail(idx): // idx coming from params 
    session = Session()

    result = session.query(
        Report
    ).filter(
        Report.report_id == idx
    ).all()

    return jsonify({
        'data': [result.serialized for result in results]
    })
Run Code Online (Sandbox Code Playgroud)