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

将 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


大家讲道理
大家讲道理

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

全員に返信 (1)
代言

为什么不用 pickle? 还是说因为必须序列化成 JSON?

いいねを押す+0
    最新のダウンロード
    詳細>
    ウェブエフェクト
    公式サイト
    サイト素材
    フロントエンドテンプレート
    私たちについて 免責事項 Sitemap
    PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!