2016/11/12
将 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 ABOUTYOU
ABOUTYOU 
					撒科打诨
 
					侃侃尔雅
 随时随地看视频慕课网APP
随时随地看视频慕课网APP
相关分类