在 suds 中添加属性

发布于 2024-10-31 02:49:06 字数 385 浏览 0 评论 0原文

我必须使用 suds 和 Python 执行肥皂请求

<soap:Body> 
    <registerOrder> 
        <order merchantOrderNumber="" description="" amount=""  currency=""  language=""  xmlns=""> 
             <returnUrl>http://mysafety.com</returnUrl> 
        </order> 
    </registerOrder> 
</soap:Body>

如何在 registerOrder 中添加属性?

I have to do soap request with suds and Python

<soap:Body> 
    <registerOrder> 
        <order merchantOrderNumber="" description="" amount=""  currency=""  language=""  xmlns=""> 
             <returnUrl>http://mysafety.com</returnUrl> 
        </order> 
    </registerOrder> 
</soap:Body>

How to add an attribute in registerOrder?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

沫雨熙 2024-11-07 02:49:06

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()

A more dynamic version of the MessagePlugin would be:

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))

Usage:

client = Client(url)
# method 1
client.options.plugins = [_AttributePlugin(foo='bar')]
response = client.service.method1()
client.options.plugins = []
# method 2
response = client.service.method2()
梦亿 2024-11-07 02:49:06

suds 文档中搜索 MessagePlugin。编组选项就是您要搜索的选项。您需要将其作为插件添加到客户端中:

self.client = Client(url, plugins=[MyPlugin()])

在编组方法中搜索 context.envelope childs。 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"))

我上周就坐在这个位置,所以它可能会为你节省一些时间:)

In suds documentation search for a MessagePlugin. The marshalled option is what you're searching for. You need to add it into your client as a plugin:

self.client = Client(url, plugins=[MyPlugin()])

In marshalled method search for context.envelope childs. The python's vars() function is very useful in this place. As I think, It should like something like this for you:

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"))

I was sitting at this for last week, so might it'll save some time for you :)

七七 2024-11-07 02:49:06

您可以使用 __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 分支。

You can use the __inject Client option to inject a particular 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})

Also, I prefer using suds-jurko https://pypi.python.org/pypi/suds-jurko/0.6 which is a fork of suds that is actively maintained.

一场信仰旅途 2024-11-07 02:49:06

我已重用 https://fedorahosted.org/suds/ticket/21 并调整了代码使用这个想法。按如下方式更改 SUDS,并

Client.<method>(param1=value1, ... , attributes={'attrName1':'attrVal1'} )

根据需要使用“attrName1”属性调用“方法”。

--- a/website/suds/bindings/binding.py
+++ b/website/suds/bindings/binding.py
@@ -24,6 +24,7 @@ from suds.sax import Namespace
 from suds.sax.parser import Parser
 from suds.sax.document import Document
 from suds.sax.element import Element
+from suds.sax.attribute import Attribute
 from suds.sudsobject import Factory, Object
 from suds.mx import Content
 from suds.mx.literal import Literal as MxLiteral
@@ -101,7 +102,7 @@ class Binding:
         """
         raise Exception, 'not implemented'

-    def get_message(self, method, args, kwargs):
+    def get_message(self, method, args, kwargs, attributes=None):
         """
         Get the soap message for the specified method, args and soapheaders.
         This is the entry point for creating the outbound soap message.
@@ -115,11 +116,23 @@ class Binding:
         @rtype: L{Document}
         """

+        if attributes:
+            pass
+            # moved to suds/bindings/document.py
+
+            #print method
+            #for name, val in attributes.items():
+            #    method.attributes.append(Attribute(name, val))
+
+
         content = self.headercontent(method)
         header = self.header(content)
-        content = self.bodycontent(method, args, kwargs)
+        content = self.bodycontent(method, args, kwargs, attributes=attributes)
         body = self.body(content)
         env = self.envelope(header, body)
+        #if attributes:
+        #    print content
+        #    1/0
         if self.options().prefixes:
             body.normalizePrefixes()
             env.promotePrefixes()
@@ -535,4 +548,4 @@ class PartElement(SchemaElement):
             return self
         else:
             return self.__resolved
-    
\ No newline at end of file
+    
diff --git a/website/suds/bindings/document.py b/website/suds/bindings/document.py
index edd9422..0c84753 100644
--- a/website/suds/bindings/document.py
+++ b/website/suds/bindings/document.py
@@ -38,7 +38,7 @@ class Document(Binding):
     (multiple message parts), must present a I{document} view for that method.
     """

-    def bodycontent(self, method, args, kwargs):
+    def bodycontent(self, method, args, kwargs, attributes=None):
         #
         # The I{wrapped} vs I{bare} style is detected in 2 ways.
         # If there is 2+ parts in the message then it is I{bare}.
@@ -54,6 +54,12 @@ class Document(Binding):
         else:
             root = []
         n = 0
+
+        if attributes:
+            #print root.__class__
+            for name, val in attributes.items():
+                root.set(name, val)
+
         for pd in self.param_defs(method):
             if n < len(args):
                 value = args[n]
diff --git a/website/suds/client.py b/website/suds/client.py
index 8b4f258..f80e36a 100644
--- a/website/suds/client.py
+++ b/website/suds/client.py
@@ -592,7 +592,10 @@ class SoapClient:
         timer.start()
         result = None
         binding = self.method.binding.input
-        soapenv = binding.get_message(self.method, args, kwargs)
+        attributes = kwargs.get('attributes', None)
+        if attributes:
+            del kwargs['attributes']
+        soapenv = binding.get_message(self.method, args, kwargs, attributes)
         timer.stop()
         metrics.log.debug(
                 "message for '%s' created: %s",
@@ -841,4 +844,4 @@ class RequestContext:
         @type error: A suds I{TransportError}.
         """
         return self.client.failed(self.binding, error)
-        
\ No newline at end of file
+        

I have reused https://fedorahosted.org/suds/ticket/21 and have adapted the code to use the idea. Change SUDS as below and use

Client.<method>(param1=value1, ... , attributes={'attrName1':'attrVal1'} )

to call 'method' with the 'attrName1' attribute as wanted.

--- a/website/suds/bindings/binding.py
+++ b/website/suds/bindings/binding.py
@@ -24,6 +24,7 @@ from suds.sax import Namespace
 from suds.sax.parser import Parser
 from suds.sax.document import Document
 from suds.sax.element import Element
+from suds.sax.attribute import Attribute
 from suds.sudsobject import Factory, Object
 from suds.mx import Content
 from suds.mx.literal import Literal as MxLiteral
@@ -101,7 +102,7 @@ class Binding:
         """
         raise Exception, 'not implemented'

-    def get_message(self, method, args, kwargs):
+    def get_message(self, method, args, kwargs, attributes=None):
         """
         Get the soap message for the specified method, args and soapheaders.
         This is the entry point for creating the outbound soap message.
@@ -115,11 +116,23 @@ class Binding:
         @rtype: L{Document}
         """

+        if attributes:
+            pass
+            # moved to suds/bindings/document.py
+
+            #print method
+            #for name, val in attributes.items():
+            #    method.attributes.append(Attribute(name, val))
+
+
         content = self.headercontent(method)
         header = self.header(content)
-        content = self.bodycontent(method, args, kwargs)
+        content = self.bodycontent(method, args, kwargs, attributes=attributes)
         body = self.body(content)
         env = self.envelope(header, body)
+        #if attributes:
+        #    print content
+        #    1/0
         if self.options().prefixes:
             body.normalizePrefixes()
             env.promotePrefixes()
@@ -535,4 +548,4 @@ class PartElement(SchemaElement):
             return self
         else:
             return self.__resolved
-    
\ No newline at end of file
+    
diff --git a/website/suds/bindings/document.py b/website/suds/bindings/document.py
index edd9422..0c84753 100644
--- a/website/suds/bindings/document.py
+++ b/website/suds/bindings/document.py
@@ -38,7 +38,7 @@ class Document(Binding):
     (multiple message parts), must present a I{document} view for that method.
     """

-    def bodycontent(self, method, args, kwargs):
+    def bodycontent(self, method, args, kwargs, attributes=None):
         #
         # The I{wrapped} vs I{bare} style is detected in 2 ways.
         # If there is 2+ parts in the message then it is I{bare}.
@@ -54,6 +54,12 @@ class Document(Binding):
         else:
             root = []
         n = 0
+
+        if attributes:
+            #print root.__class__
+            for name, val in attributes.items():
+                root.set(name, val)
+
         for pd in self.param_defs(method):
             if n < len(args):
                 value = args[n]
diff --git a/website/suds/client.py b/website/suds/client.py
index 8b4f258..f80e36a 100644
--- a/website/suds/client.py
+++ b/website/suds/client.py
@@ -592,7 +592,10 @@ class SoapClient:
         timer.start()
         result = None
         binding = self.method.binding.input
-        soapenv = binding.get_message(self.method, args, kwargs)
+        attributes = kwargs.get('attributes', None)
+        if attributes:
+            del kwargs['attributes']
+        soapenv = binding.get_message(self.method, args, kwargs, attributes)
         timer.stop()
         metrics.log.debug(
                 "message for '%s' created: %s",
@@ -841,4 +844,4 @@ class RequestContext:
         @type error: A suds I{TransportError}.
         """
         return self.client.failed(self.binding, error)
-        
\ No newline at end of file
+        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文