Python 创建一个支持json序列化的类,用于芹菜
我在用芹菜做一些后台任务。其中一个任务返回我创建的python类。考虑到关于使用pickle的警告,我想使用json来序列化和反序列化这个类 是否有一种简单的内置方式来实现这一点 该类非常简单,它包含3个属性,所有这些属性都是命名元组的列表。它包含两个对属性执行某些计算的方法 我的想法是序列化/反序列化3个属性,因为这定义了类 这是我对编码器的想法,但我不确定如何再次解码数据Python 创建一个支持json序列化的类,用于芹菜,python,json,celery,Python,Json,Celery,我在用芹菜做一些后台任务。其中一个任务返回我创建的python类。考虑到关于使用pickle的警告,我想使用json来序列化和反序列化这个类 是否有一种简单的内置方式来实现这一点 该类非常简单,它包含3个属性,所有这些属性都是命名元组的列表。它包含两个对属性执行某些计算的方法 我的想法是序列化/反序列化3个属性,因为这定义了类 这是我对编码器的想法,但我不确定如何再次解码数据 import json class JSONSerializable(object): def __repr_
import json
class JSONSerializable(object):
def __repr__(self):
return json.dumps(self.__dict__)
class MySimpleClass(JSONSerializable):
def __init__(self, p1, p2, p3): # I only care about p1, p2, p3
self.p1 = p1
self.p2 = p2
self.p3 = p2
self.abc = p1 + p2 + p2
def some_calc(self):
...
首先但并非最不重要的一点:针对pickle的警告主要是如果您可能让第三方在工作流中注入pickle数据。如果您确定您自己的系统正在创建要使用的所有pickle数据,则根本不存在安全问题。至于兼容性,对于Pickle文件的生产者和消费者来说,如果您使用相同的Python版本,那么它相对容易处理,并且是自动的 也就是说,对于JSON,您必须创建一个子类-每个子类都需要作为
cls
参数传递给所有JSON.dump
和JSON.load
调用
建议编码器上的default
方法将类\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
及其\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu名称和标识符键(比如\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
在编码器上,检查\uuuuuu custom\uuuuuuu
键,然后使用\uuuuuuu new\uuuuuuu
方法实例化一个类,并填充其dict。与pickle一样,在类\uuuuu init\uuuuuuu
上触发的副作用不会运行
稍后,您可以增强解码器和编码器,以便它们在类中搜索只能处理所需属性的\uu json\u encode\uu
方法
示例实现:
import json
class GenericJSONEncoder(json.JSONEncoder):
def default(self, obj):
try:
return super().default(obj)
except TypeError:
pass
cls = type(obj)
result = {
'__custom__': True,
'__module__': cls.__module__,
'__name__': cls.__name__,
'data': obj.__dict__ if not hasattr(cls, '__json_encode__') else obj.__json_encode__
}
return result
class GenericJSONDecoder(json.JSONDecoder):
def decode(self, str):
result = super().decode(str)
if not isinstance(result, dict) or not result.get('__custom__', False):
return result
import sys
module = result['__module__']
if not module in sys.modules:
__import__(module)
cls = getattr(sys.modules[module], result['__name__'])
if hasattr(cls, '__json_decode__'):
return cls.__json_decode__(result['data'])
instance = cls.__new__(cls)
instance.__dict__.update(result['data'])
return instance
控制台上的交互式测试:
In [36]: class A:
...: def __init__(self, a):
...: self.a = a
...:
In [37]: a = A('test')
In [38]: b = json.loads(json.dumps(a, cls=GenericJSONEncoder), cls=GenericJSONDecoder)
In [39]: b.a
Out[39]: 'test'
这里是@jsbueno提供的伟大解决方案的一个改进版本,它也适用于嵌套的自定义类型
import json
import collections
import six
def is_iterable(arg):
return isinstance(arg, collections.Iterable) and not isinstance(arg, six.string_types)
class GenericJSONEncoder(json.JSONEncoder):
def default(self, obj):
try:
return super().default(obj)
except TypeError:
pass
cls = type(obj)
result = {
'__custom__': True,
'__module__': cls.__module__,
'__name__': cls.__name__,
'data': obj.__dict__ if not hasattr(cls, '__json_encode__') else obj.__json_encode__
}
return result
class GenericJSONDecoder(json.JSONDecoder):
def decode(self, str):
result = super().decode(str)
return GenericJSONDecoder.instantiate_object(result)
@staticmethod
def instantiate_object(result):
if not isinstance(result, dict): # or
if is_iterable(result):
return [GenericJSONDecoder.instantiate_object(v) for v in result]
else:
return result
if not result.get('__custom__', False):
return {k: GenericJSONDecoder.instantiate_object(v) for k, v in result.items()}
import sys
module = result['__module__']
if module not in sys.modules:
__import__(module)
cls = getattr(sys.modules[module], result['__name__'])
if hasattr(cls, '__json_decode__'):
return cls.__json_decode__(result['data'])
instance = cls.__new__(cls)
data = {k: GenericJSONDecoder.instantiate_object(v) for k, v in result['data'].items()}
instance.__dict__.update(data)
return instance
class C:
def __init__(self):
self.c = 133
def __repr__(self):
return "C<" + str(self.__dict__) + ">"
class B:
def __init__(self):
self.b = {'int': 123, "c": C()}
self.l = [123, C()]
self.t = (234, C())
self.s = "Blah"
def __repr__(self):
return "B<" + str(self.__dict__) + ">"
class A:
class_y = 13
def __init__(self):
self.x = B()
def __repr__(self):
return "A<" + str(self.__dict__) + ">"
def dumps(obj, *args, **kwargs):
return json.dumps(obj, *args, cls=GenericJSONEncoder, **kwargs)
def dump(obj, *args, **kwargs):
return json.dump(obj, *args, cls=GenericJSONEncoder, **kwargs)
def loads(obj, *args, **kwargs):
return json.loads(obj, *args, cls=GenericJSONDecoder, **kwargs)
def load(obj, *args, **kwargs):
return json.load(obj, *args, cls=GenericJSONDecoder, **kwargs)
印刷品:
A<{'x': B<{'b': {'int': 123, 'c': C<{'c': 133}>}, 'l': [123, C<{'c': 133}>], 't': [234, C<{'c': 133}>], 's': 'Blah'}>}>
请注意,如果类型包含类似列表或元组的集合,则在解码期间无法还原集合的实际类型。这是因为,当编码为json时,所有这些集合都将转换为列表。太好了,所有的pickle数据都在我的控制范围内,所以我想如果我继续使用pickle就好了。这太棒了!非常感谢!我想pip安装jsbueno_序列化程序
这是PyPI上的吗?还没有-我已经粘贴了它作为要点:我们可以在今天晚些时候打包。可能是
A<{'x': B<{'b': {'int': 123, 'c': C<{'c': 133}>}, 'l': [123, C<{'c': 133}>], 't': [234, C<{'c': 133}>], 's': 'Blah'}>}>
A<{'x': {'__custom__': True, '__module__': '__main__', '__name__': 'B', 'data': {'b': {'int': 123, 'c': {'__custom__': True, '__module__': '__main__', '__name__': 'C', 'data': {'c': 133}}}, 'l': [123, {'__custom__': True, '__module__': '__main__', '__name__': 'C', 'data': {'c': 133}}], 't': [234, {'__custom__': True, '__module__': '__main__', '__name__': 'C', 'data': {'c': 133}}], 's': 'Blah'}}}>