SQLAlchemy 对象进行 JSON 序列化, 有什么好的方法( 集思广益 )?
大家讲道理
大家讲道理 2016-11-12 11:09:04
0
1
930

将 SQLAlchemy 对象, 转化为Python-dict, 或者序列化成 JSON, 主要实现:

to_dict()

to_json()

我自己实现了一种做法, 但是总感觉还有些问题( 但是又说不清楚 ), 大家有什么比较好的办法?

相关代码

将这两个方法直接绑定到Base上面, 则继承Base的类, 都能使用

def _gen_tuple(self):
    def convert_datetime(value):
        if value:
            return value.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return ""

    for col in self.__table__.columns:
        if isinstance(col.type, DateTime):
            value = convert_datetime(getattr(self, col.name))
        elif isinstance(col.type, Numeric):
            value = float(getattr(self, col.name))
        else:
            value = getattr(self, col.name)
        yield (col.name, value)


def to_dict(self):
    return dict(self._gen_tuple())


def to_json(self):
    return json.dumps(self.to_dict())

Base._gen_tuple = _gen_tuple
Base.to_dict = to_dict
Base.to_json = to_json


大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

répondre à tous(1)
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!