覆盖jsonpickle的__getstate__但不支持deepcopy

时间:2018-04-05 03:31:01

标签: python jsonpickle

我希望在pickling对象实例(发送到json-api端点)时隐藏一些(私有)属性。我已经为这个效果添加了__getstate__函数,但副作用是deepcopy也使用了__getstate__。深度复制实例时,我不想排除任何属性,是否有办法区分调用函数?

class LevelMixin(object):

def __init___(self...):
    ....

def __getstate__(self):
    """
    If pickleable hide all private and weak refs.
    """

    if not getattr(self, '_unpickleable', True):

        __state = self.__dict__.copy()
        keep_private = ['_unpickleable', 'unpickleable']
        state = {}

        for k, v in __state.items():
            if v is not None and v != "None" and k not in keep_private and not callable(v):
                if k.startswith('_') and not k.startswith('__'):
                    state[k[1:]] = v  # if key starts with single underscore, remove it
                else:
                    state[k] = v
    else:
        state = self.__dict__.copy()
    return state

检查堆栈会告诉我何时进行深度检查'或者' _flatten_obj_instance'是调用函数,但我知道在生产代码中检查这些是不好的做法。关于如何避免使用深度复制的代码,但是在jsonpickle中使用它的任何想法?

1 个答案:

答案 0 :(得分:0)

如果这有助于任何人,我决定注册更详细的custom handlers,并明确说明de / serialization中数据的表示形式,如下所示:

import jsonpickle.handlers

@jsonpickle.handlers.register(LevelMixin, base=True)
class LevelMixinHandler(jsonpickle.handlers.BaseHandler):
    """Custom jsonpickle handler for LevelMixin"""

    def flatten(self, obj, data):
        data['name'] = obj.name
        data['type'] = obj.type
        data['pretty_name'] = obj.pretty_name
        data['description'] = obj.description
        ...
        return data

    def restore(self, obj):
        pass