15

I'm using SQLAlchemy extension with Flask. While serializing my models (which are also used for database operations) using jsonpickle, I want some specific attributes to be ignored. Is there a way that allows me to set those rules?

SQLAlchemy adds an attribute named _sa_instance_state to the object. In a word, I do not want this field to be in the JSON output.

4

2 回答 2

23

你不能告诉默认的类pickler忽略一些东西,不。

jsonpickle 确实支持pickle模块 __getstate____setstate__方法。如果您的类实现了这两种方法,则返回的任何内容都将用于jsonpickle表示状态。这两种方法都需要实现。

如果__getstate__未实现,则使用属性,因此您自己的版本只需要使用相同的字典,删除键即可完成:jsonpickle__dict___sa_instance_state

def __getstate__(self):
    state = self.__dict__.copy()
    del state['_sa_instance_state']
    return state

def __setstate__(self, state):
    self.__dict__.update(state)

无论__getstate__返回什么都将被进一步递归处理,无需担心在那里处理子对象。

如果添加__getstate__and__setstate__不是一个选项,您还可以为您的类注册一个自定义序列化处理程序;缺点是虽然__getstate__可以只返回字典,但自定义处理程序需要返回完全展平的值。

于 2013-08-09T13:30:28.790 回答
0

这将帮助其他人完成任务:

在像您的自定义jsonpickle包这样的包中创建一个这样的类:

class SetGetState:
    def __getstate__(self):
        state = self.__dict__.copy()
        try:
            class_name = '_' + self.__class__.__name__ + '__'
            new_items = {key:value for key, value in state.items() if class_name not in key}
            return new_items
        except KeyError:
            pass
        return state

并且继承这个类中不需要私有属性序列化

class Availability(jsonpickle.SetGetState):
    pass
于 2018-12-23T17:43:48.237 回答