为什么我不能在pysimplesoap中设置SOAP标头?

时间:2015-06-01 19:19:32

标签: python web-services soap wsdl

我收到了一些用于调用SOAP服务的示例php代码,我现在需要将其转换为Python。在php代码中,他们按如下方式设置标题:

$auth = array();
$auth['token'] = 'xxx';
if ($auth) {
    // add auth header
    $this->clients[$module]->__setSoapHeaders(
        new SoapHeader(
            $namespace, 
            'auth', 
            $auth
        )
    );
}

因此auth标题应如下所示:['token' => 'xxx']。然后我将wsdl加载到SoapUI,这给了我以下示例xml:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sub="https://example.com/path/to/sub">
   <soapenv:Header>
      <sub:auth>
         <token>?</token>
         <!--Optional:-->
         <user_id>?</user_id>
         <!--Optional:-->
         <user_token>?</user_token>
      </sub:auth>
   </soapenv:Header>
   <soapenv:Body>
      <sub:customer_logos_pull>
         <!--Optional:-->
         <language>?</language>
         <!--Optional:-->
         <limit>?</limit>
         <!--Optional:-->
         <options_utc>?</options_utc>
      </sub:customer_logos_pull>
   </soapenv:Body>
</soapenv:Envelope>

在pysimplesoap中我现在尝试这样的事情:

from pysimplesoap.client import SoapClient

WSDL = 'https://example.com/some/path/sub.wsdl'
TOKEN = 'xxx'

client = SoapClient(wsdl=WSDL, trace=True)
client['auth'] = {'token': TOKEN}
print client.customer_logos_pull({})

但是我收到错误ExpatError: not well-formed (invalid token): line 1, column 0,这是有道理的,因为在记录的xml中我看到标题是空的:

<soap:Header/>

我尝试通过在sub:之前加auth来改变代码:client['sub:auth'] = {'token': TOKEN},但我得到了同样的错误。

有人知道我在这里做错了什么吗?欢迎所有提示!

1 个答案:

答案 0 :(得分:3)

所以我认为我们可以使用suds库来解决

以下是如何发送包含标头的SOAP请求的非常基本的示例:

示例:

from suds.sax.element import Element 

client = client(url) 
ssnns = ('ssn', 'http://namespaces/sessionid') 
ssn = Element('SessionID', ns=ssnns).setText('123') 
client.set_options(soapheaders=ssn)  
result = client.service.addPerson(person)

这是您发送以下标题的示例:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP ENC="http://www.w3.org/2003/05/soap-encoding">
    <ssn:SessionID SOAP-ENV:mustUnderstand="true">123</ssn:SessionID>
 </SOAP-ENV:Header>

NB:我实际上并没有尝试本身,因为我无法访问任何我可以测试的现成SOAP / XML服务!

因此,在您的特定示例中,您将执行以下操作:

>>> from suds.sax.element import Element
>>> subns = ("sub", "http://namespaces/sub")
>>> sub = Element("auth", ns=subns)
>>> token = Element("token").setText("?")
>>> user_id = Element("user_id").setText("?")
>>> user_token = Element("user_token").setText("?")
>>> sub.append(token)
Element (prefix=sub, name=auth)
>>> sub.append(user_id)
Element (prefix=sub, name=auth)
>>> sub.append(user_token)
Element (prefix=sub, name=auth)
>>> print(sub.str())
<sub:auth xmlns:sub="http://namespaces/sub">
   <token>?</token>
   <user_id>?</user_id>
   <user_token>?</user_token>
</sub:auth>

然后在set_options()对象上调用client

client.set_options(soapheaders=sub)

您可以 使用suds轻松安装pip,方法是:

$ pip install suds