【问题标题】:Serialize SQLAlchemy output to a JSON including column names将 SQLAlchemy 输出序列化为 JSON,包括列名
【发布时间】:2015-12-27 05:24:39
【问题描述】:

我决定迁移我的 Django 项目以使用 SqlAlchemy 而不是 Django ORM,我正在尝试将我的 SqlAlchemy 输出序列化为包含列名的 JSON。

在 Django 中,我有以下代码:

logs = Log.objects.values('log_timestamp', 'message', 'exception', 'level__level', 'job_info__job_name', 'machine', 'user', 'job_report__id').filter(job_info__app_id = app_id).order_by('-time_added')[:1]
logs = json.dumps(list(logs), default=views_utils.default_json_serializer)
print(logs)

这里是一个输出示例(包含列名):

[{"user": "user", "level__level": "INFO", "message": "this is a message", "log_timestamp": null, "job_info__job_name": "MongoDB_Maintenance", "exception": "exception details", "machine": "machine", "job_report__id": 65}]

这是我的 SqlAlchemy 代码:

res = session.query(func.DATETIME(LogObj.time_added), LogObj.message, LogObj.exception, LogLevelObj.level, LogObj.machine, LogObj.user).\
                  join(PeriodicJobInfoObj, LogLevelObj, LogObj,aliased=True).\
                  filter(PeriodicJobInfoObj.app_id == app_id).\
                  order_by(desc(LogObj.time_added))[:1]
res = json.dumps(res, default=views_utils.default_json_serializer)
print(res)

输出不包含列名:

[["2015-09-28 15:36:33", "this is a message", "exception details", "CRITICAL", "machine", "user"]]

default_json_serializer 代码:

def default_json_serializer(obj):
    """Default JSON serializer."""
    import calendar, datetime

    if isinstance(obj, datetime.datetime):
        if obj.utcoffset() is not None:
            obj = obj - obj.utcoffset()
    millis = int(
        calendar.timegm(obj.timetuple()) * 1000 +
        obj.microsecond / 1000
    )
    return millis

我怎样才能像 Django 一样实现类似的输出? (使用 Python 3.4.2)

【问题讨论】:

    标签: json django python-3.x sqlalchemy


    【解决方案1】:

    我已经设法做到了:

    def alchemyencoder(obj):
      if isinstance(obj, datetime.date):
        return obj.isoformat()
      elif isinstance(obj, decimal.Decimal):
        return float(obj)
    

    我在通过以下方式检索记录时使用上述编码器:

    row = conn.execute(Model.__table__.select())
    d = json.dumps([dict(r) for r in row], default=alchemyencoder)
    d = json.JSONDecoder().decode(d)
    print(d)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-28
      • 2021-06-27
      • 2017-06-09
      • 1970-01-01
      相关资源
      最近更新 更多