python - SQLAlchemy 对象进行 JSON 序列化, 有什么好的方法( 集思广益 )?
大家讲道理
大家讲道理 2017-04-18 09:54:23
0
3
652

2016/11/12

问题

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

  1. to_dict()

  2. 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
大家讲道理
大家讲道理

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

reply all (3)
阿神

Thanks for the invitation

I can understand what you want to serialize. I guess you want to achieve the following effect:

user = User.query.filter_by(id=id).first() response = jsonify(user.to_json())

I have been pursuing such a method before, but by directly converting the fields in an object intojson意味着很多前端不需要的字段也会一起返回。个人并不是很喜欢,我倾向于前端需要什么就给什么。所以这样简单的to_json操作并不是很好,除非你结合一些序列化的插件,可以很好的控制哪些需要返回给前端的,不过看了一圈这样的插件,没有使用起来很方便的。反而是自己组装来的更灵活,所以渐渐的就不再去追寻这样的方法了。如果你比较喜欢这样的可以去看看django-rest-frameworkthis 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?

      PHPzhong

      mongodb + mongokit should be more suitable for you

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!