好的我正在努力改进python,所以我不确定这是我正在做的事情的正确方法,但这是我目前的问题......
我需要通过SOAP方法获取一些信息,现在只使用部分信息,但将整个结果存储起来以备将来使用(我们需要尽可能少地使用该服务)。查找访问服务的最佳方式我认为suds是要走的路,它很简单,就像获取数据的魅力一样。但是现在我想以某种方式保存结果,最好是序列化/在数据库中,这样我以后可以把它拉出来并使用它。
最好的方法是什么,看起来像pickle / json不是一个选择?谢谢!
更新 阅读How can I pickle suds results?的最佳答案让我更好地了解为什么这不是一个选项,我想我是在用我需要的信息重新创建一个基本对象?
答案 0 :(得分:32)
我一直在使用以下方法将Suds对象转换为JSON:
from suds.sudsobject import asdict
def recursive_asdict(d):
"""Convert Suds object into serializable format."""
out = {}
for k, v in asdict(d).iteritems():
if hasattr(v, '__keylist__'):
out[k] = recursive_asdict(v)
elif isinstance(v, list):
out[k] = []
for item in v:
if hasattr(item, '__keylist__'):
out[k].append(recursive_asdict(item))
else:
out[k].append(item)
else:
out[k] = v
return out
def suds_to_json(data):
return json.dumps(recursive_asdict(data))
答案 1 :(得分:6)
是的,我确认了你在你提到的答案中给出的解释 - 动态生成的类不容易被选择(也不容易序列化),你需要提取所有的状态信息,pickle 那个状态,如果你真的坚持使用它,就会重新检索棘手的漏洞对象; - )。
答案 2 :(得分:5)
我为suds的Object intance做了一个虚拟类的实现,然后能够序列化。 FakeSudsInstance的行为类似于原始的Suds Object实例,见下文:
from suds.sudsobject import Object as SudsObject
class FakeSudsNode(SudsObject):
def __init__(self, data):
SudsObject.__init__(self)
self.__keylist__ = data.keys()
for key, value in data.items():
if isinstance(value, dict):
setattr(self, key, FakeSudsNode(value))
elif isinstance(value, list):
l = []
for v in value:
if isinstance(v, list) or isinstance(v, dict):
l.append(FakeSudsNode(v))
else:
l.append(v)
setattr(self, key, l)
else:
setattr(self, key, value)
class FakeSudsInstance(SudsObject):
def __init__(self, data):
SudsObject.__init__(self)
self.__keylist__ = data.keys()
for key, value in data.items():
if isinstance(value, dict):
setattr(self, key, FakeSudsNode(value))
else:
setattr(self, key, value)
@classmethod
def build_instance(cls, instance):
suds_data = {}
def node_to_dict(node, node_data):
if hasattr(node, '__keylist__'):
keys = node.__keylist__
for key in keys:
if isinstance(node[key], list):
lkey = key.replace('[]', '')
node_data[lkey] = node_to_dict(node[key], [])
elif hasattr(node[key], '__keylist__'):
node_data[key] = node_to_dict(node[key], {})
else:
if isinstance(node_data, list):
node_data.append(node[key])
else:
node_data[key] = node[key]
return node_data
else:
if isinstance(node, list):
for lnode in node:
node_data.append(node_to_dict(lnode, {}))
return node_data
else:
return node
node_to_dict(instance, suds_data)
return cls(suds_data)
现在,在suds电话之后,例如下面:
# Now, after a suds call, for example below
>>> import cPickle as pickle
>>> suds_intance = client.service.SomeCall(account, param)
>>> fake_suds = FakeSudsInstance.build_instance(suds_intance)
>>> dumped = pickle.dumps(fake_suds)
>>> loaded = pickle.loads(dumped)
我希望它有所帮助。
答案 3 :(得分:2)
以下是我在研究和找到答案之前提出的问题。这对我来说非常适用于复杂的suds响应以及其他对象,例如__builtins__
,因为解决方案是suds不可知的:
import datetime
def object_to_dict(obj):
if isinstance(obj, (str, unicode, bool, int, long, float, datetime.datetime, datetime.date, datetime.time)):
return obj
data_dict = {}
try:
all_keys = obj.__dict__.keys() # vars(obj).keys()
except AttributeError:
return obj
fields = [k for k in all_keys if not k.startswith('_')]
for field in fields:
val = getattr(obj, field)
if isinstance(val, (list, tuple)):
data_dict[field] = []
for item in val:
data_dict[field].append(object_to_dict(item))
else:
data_dict[field] = object_to_dict(val)
return data_dict
此解决方案有效且实际上更快。它也适用于没有__keylist__
属性的对象。
我在复杂的suds输出对象上运行了100次基准测试,此解决方案运行时间为0.04到.052秒(平均0.045724287)。虽然上面的recursive_asdict
解决方案在.082到0.102秒内运行,所以几乎翻倍(平均0.0829765582)。
然后我回到绘图板并重新执行该功能以获得更多性能,并且它不需要datetime
导入。我利用__keylist__
属性,因此这不适用于__builtins__
等其他对象,但对于suds对象输出效果很好:
def fastest_object_to_dict(obj):
if not hasattr(obj, '__keylist__'):
return obj
data = {}
fields = obj.__keylist__
for field in fields:
val = getattr(obj, field)
if isinstance(val, list): # tuple not used
data[field] = []
for item in val:
data[field].append(fastest_object_to_dict(item))
else:
data[field] = fastest_object_to_dict(val)
return data
运行时间为0.18 - 0.033秒(平均0.0260889721),因此比recursive_asdict
解决方案快4倍。
答案 4 :(得分:2)
上面提到的解决方案丢失了有关类名的有价值的信息 - 它在某些库中很有价值,例如DFP客户端https://github.com/googleads/googleads-python-lib,其中实体类型可能以动态生成的类名编码(即 TemplateCreative / <强> ImageCreative 强>)
这里是我使用的解决方案,它保留了类名并恢复了dict-serialized对象而没有数据丢失(除了 suds.sax.text.Text ,它将被转换为常规的unicode对象和也许还有一些其他类型我还没碰到过)
from suds.sudsobject import asdict, Factory as SudsFactory
def suds2dict(d):
"""
Suds object serializer
Borrowed from https://stackoverflow.com/questions/2412486/serializing-a-suds-object-in-python/15678861#15678861
"""
out = {'__class__': d.__class__.__name__}
for k, v in asdict(d).iteritems():
if hasattr(v, '__keylist__'):
out[k] = suds2dict(v)
elif isinstance(v, list):
out[k] = []
for item in v:
if hasattr(item, '__keylist__'):
out[k].append(suds2dict(item))
else:
out[k].append(item)
else:
out[k] = v
return out
def dict2suds(d):
"""
Suds object deserializer
"""
out = {}
for k, v in d.iteritems():
if isinstance(v, dict):
out[k] = dict2suds(v)
elif isinstance(v, list):
out[k] = []
for item in v:
if isinstance(item, dict):
out[k].append(dict2suds(item))
else:
out[k].append(item)
else:
out[k] = v
return SudsFactory.object(out.pop('__class__'), out)
答案 5 :(得分:1)
我更新了recursive_asdict
示例followed this tutorial以与python3兼容(items
而不是iteritems
)。
from suds.sudsobject import asdict
from suds.sax.text import Text
def recursive_asdict(d):
"""
Recursively convert Suds object into dict.
We convert the keys to lowercase, and convert sax.Text
instances to Unicode.
Taken from:
https://stackoverflow.com/a/15678861/202168
Let's create a suds object from scratch with some lists and stuff
>>> from suds.sudsobject import Object as SudsObject
>>> sudsobject = SudsObject()
>>> sudsobject.Title = "My title"
>>> sudsobject.JustAList = [1, 2, 3]
>>> sudsobject.Child = SudsObject()
>>> sudsobject.Child.Title = "Child title"
>>> sudsobject.Child.AnotherList = ["4", "5", "6"]
>>> childobject = SudsObject()
>>> childobject.Title = "Another child title"
>>> sudsobject.Child.SudObjectList = [childobject]
Now see if this works:
>>> result = recursive_asdict(sudsobject)
>>> result['title']
'My title'
>>> result['child']['anotherlist']
['4', '5', '6']
"""
out = {}
for k, v in asdict(d).items():
k = k.lower()
if hasattr(v, '__keylist__'):
out[k] = recursive_asdict(v)
elif isinstance(v, list):
out[k] = []
for item in v:
if hasattr(item, '__keylist__'):
out[k].append(recursive_asdict(item))
else:
out[k].append(
item.title() if isinstance(item, Text) else item)
else:
out[k] = v.title() if isinstance(v, Text) else v
return out