将Namespace添加到Suds中的默认WSSE安全对象

时间:2011-08-23 22:28:03

标签: python suds

我理解如何向SOAP请求添加标头。但是这会产生一个与我需要传递的标题不匹配的标题。返回此标题:

   <SOAP-ENV:Header>
      <wsse:Security mustUnderstand="true">
         <wsse:UsernameToken>
            <wsse:Username>CABLE</wsse:Username>
            <wsse:Password>CABLE</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </SOAP-ENV:Header>

但是,我需要修改该标头的名称空间以传递Security对象和UsernameToken对象的特定名称空间。我似乎无法弄清楚如何覆盖提供的默认值。

<soapenv:Header>
 <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/07/secext">
       http://schemas.xmlsoap.org/ws/2002/07/secext
 <wsse:UsernameToken xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility">
 <wsse:Username>CABLE</wsse:Username>
 <wsse:Password Type="wsse:PasswordText">CABLE</wsse:Password>
 </wsse:UsernameToken>
 </wsse:Security>
</soapenv:Header>

以下是生成上述

的Python代码
security = Security()
token = UsernameToken('CABLE', 'CABLE')
security.tokens.append(token)
client.set_options(wsse=security)

1 个答案:

答案 0 :(得分:3)

想出来。这是答案。只需要使用ns参数

def createWSSecurityHeader(username,password):
    # Namespaces
    wsse = ('wsse', 'http://schemas.xmlsoap.org/ws/2002/07/secext')

    # Create Security Element
    security = Element('Security', ns=wsse)

    # Create UsernameToken, Username/Pass Element
    usernametoken = Element('UsernameToken', ns=wsse)
    uname = Element('Username', ns=wsse).setText(username)
    passwd = Element('Password', ns=wsse).setText(password)

    # Add Username and Password elements to UsernameToken element
    usernametoken.insert(uname)
    usernametoken.insert(passwd)

    security.insert(usernametoken)
    return security