在suds中添加属性
我需要用suds和Python发送SOAP请求
<soap:Body>
<registerOrder>
<order merchantOrderNumber="" description="" amount="" currency="" language="" xmlns="">
<returnUrl>http://mysafety.com</returnUrl>
</order>
</registerOrder>
</soap:Body>
怎么在registerOrder里添加一个属性?
4 个回答
1
你可以使用 __inject Client 这个选项来注入特定的 XML 数据。
raw_xml = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope>
<SOAP-ENV:Body>
...
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>"""
print client.service.example(__inject={'msg':raw_xml})
另外,我更喜欢使用 suds-jurko 这个库,https://pypi.python.org/pypi/suds-jurko/0.6,它是一个活跃维护的 suds 的分支版本。
5
在suds的文档中,找一下MessagePlugin。你要找的就是“marshalled”这个选项。你需要把它作为一个插件添加到你的客户端中:
self.client = Client(url, plugins=[MyPlugin()])
在“marshalled”方法中,查找context.envelope的子项。这里可以用Python的vars()函数,它非常有用。对你来说,应该像这样:
from suds.sax.attribute import Attribute
from suds.plugin import MessagePlugin
class MyPlugin(MessagePlugin):
def marshalled(self, context):
foo = context.envelope.getChild('Body').getChild('registerOrder')[0]
foo.attributes.append(Attribute("foo", "bar"))
我上周一直在研究这个,希望能为你节省一些时间 :)
8
一个更灵活的MessagePlugin版本如下:
from suds.sax.attribute import Attribute
from suds.plugin import MessagePlugin
class _AttributePlugin(MessagePlugin):
"""
Suds plug-in extending the method call with arbitrary attributes.
"""
def __init__(self, **kwargs):
self.kwargs = kwargs
def marshalled(self, context):
method = context.envelope.getChild('Body')[0]
for key, item in self.kwargs.iteritems():
method.attributes.append(Attribute(key, item))
使用方法:
client = Client(url)
# method 1
client.options.plugins = [_AttributePlugin(foo='bar')]
response = client.service.method1()
client.options.plugins = []
# method 2
response = client.service.method2()