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
Thanks for the invitation
I can understand what you want to serialize. I guess you want to achieve the following effect:
I have been pursuing such a method before, but by directly converting the fields in an object into
json
意味着很多前端不需要的字段也会一起返回。个人并不是很喜欢,我倾向于前端需要什么就给什么。所以这样简单的to_json
操作并不是很好,除非你结合一些序列化的插件,可以很好的控制哪些需要返回给前端的,不过看了一圈这样的插件,没有使用起来很方便的。反而是自己组装来的更灵活,所以渐渐的就不再去追寻这样的方法了。如果你比较喜欢这样的可以去看看django-rest-framework
this plug-in, the serialization inside may be what you want. In addition to the SQLAlchemy ORM, there is the Orator ORM, which I personally feel is pretty good. I feel comfortable just looking at the source code. You can check it out if you have the chance.So, in summary, there are no good recommendations. Of course, you can implement one yourself, and that’s about it.
Why not use pickle? Or is it because it must be serialized into JSON?
mongodb + mongokit should be more suitable for you