如何使用 Python zeep 库与 SOAP Webservice 建立连接?

问题描述

首先,这是我第一次使用 SOAP Webservice,所以我试图了解如何解释它。我所做的第一步是读取 wsdl 文件,为此我需要插入网络服务提供商提供的用户名和密码。网络服务如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
<deFinitions targetNamespace="http://infocomercial.cifin.asobancaria.com" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:intf="http://infocomercial.cifin.asobancaria.com" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://infocomercial.cifin.asobancaria.com" xmlns:tns1="http://dto.infocomercial.cifin.asobancaria.com" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
<!--WSDL created by Apache Axis version: 1.4
Built on Oct 06,2010 (02:39:27 GMT)-->
 <wsdl:types>
  <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://dto.infocomercial.cifin.asobancaria.com">
   <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
   <complexType name="ParametrosConsultaDTO">
    <sequence>
     <element name="codigoInformacion" nillable="true" type="soapenc:string"/>
     <element name="motivoConsulta" nillable="true" type="soapenc:string"/>
     <element name="numeroIdentificacion" nillable="true" type="soapenc:string"/>
     <element name="tipoIdentificacion" nillable="true" type="soapenc:string"/>
    </sequence>
   </complexType>
  </schema>
 </wsdl:types>

     <message name="consultaXmlRequest">

      <part name="in0" type="tns1:ParametrosConsultaDTO"/>

     </message>

     <message name="consultaXmlResponse">

      <part name="consultaXmlReturn" type="soapenc:string"/>

     </message>

     <message name="consultaPlanorequest">

      <part name="in0" type="tns1:ParametrosConsultaDTO"/>

     </message>

     <message name="consultaPlanoresponse">

      <part name="consultaPlanoreturn" type="soapenc:string"/>

     </message>

     <message name="cambioPasswordRequest">

      <part name="in0" type="soapenc:string"/>

     </message>

     <message name="cambioPasswordResponse">

      <part name="cambioPasswordReturn" type="soapenc:string"/>

     </message>

     <portType name="InformacionComercialWS">

      <operation name="consultaXml" parameterOrder="in0">

           <input name="consultaXmlRequest" message="intf:consultaXmlRequest"/>

           <output name="consultaXmlResponse" message="intf:consultaXmlResponse"/>

      </operation>

      <operation name="consultaPlano" parameterOrder="in0">

           <input name="consultaPlanorequest" message="intf:consultaPlanorequest"/>

           <output name="consultaPlanoresponse" message="intf:consultaPlanoresponse"/>

      </operation>

      <operation name="cambioPassword" parameterOrder="in0">

           <input name="cambioPasswordRequest" message="intf:cambioPasswordRequest"/>

           <output name="cambioPasswordResponse" message="intf:cambioPasswordResponse"/>

      </operation>

     </portType>

     <binding name="InformacionComercialSoapBinding" type="intf:InformacionComercialWS">

      <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>

      <operation name="consultaXml">

           <wsdlsoap:operation soapAction=""/>

           <input name="consultaXmlRequest">

                <wsdlsoap:body use="encoded" namespace="http://infocomercial.cifin.asobancaria.com" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

           </input>

           <output name="consultaXmlResponse">

                <wsdlsoap:body use="encoded" namespace="http://infocomercial.cifin.asobancaria.com" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

           </output>

      </operation>

      <operation name="consultaPlano">

           <wsdlsoap:operation soapAction=""/>

           <input name="consultaPlanorequest">

                <wsdlsoap:body use="encoded" namespace="http://infocomercial.cifin.asobancaria.com" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

           </input>

           <output name="consultaPlanoresponse">

                <wsdlsoap:body use="encoded" namespace="http://infocomercial.cifin.asobancaria.com" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

           </output>

      </operation>

      <operation name="cambioPassword">

           <wsdlsoap:operation soapAction=""/>

           <input name="cambioPasswordRequest">

                <wsdlsoap:body use="encoded" namespace="http://infocomercial.cifin.asobancaria.com" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

           </input>

           <output name="cambioPasswordResponse">

                <wsdlsoap:body use="encoded" namespace="http://infocomercial.cifin.asobancaria.com" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

           </output>

      </operation>

     </binding>

     <service name="InformacionComercialWSService">

      <port name="InformacionComercial" binding="intf:InformacionComercialSoapBinding">

           <wsdlsoap:address location="https://ttuweb3.universo.corp/InformacionComercialWS/services/InformacionComercial"/>

      </port>

     </service>

</deFinitions>

我可以根据这个文件解释以下内容

  • 服务名称:InformacionComercialWSService
  • 端口名称:InformacionComercial
  • 可能的操作:consultaXml、consultaPlano 和 cambioPassword

所以,根据webservice的开发环境,我需要将这个信息作为参数传递: 'codigoInformacion':"1401",'motivoConsulta':"24",'numeroIdentificacion':"80775779",'tipoIdentificacion':"1"

以下是有效的 SOAP UI 请求:

   <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:inf="http://infocomercial.cifin.asobancaria.com">
<soapenv:Header/>
<soapenv:Body>
    <inf:consultaXml soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <in0 xsi:type="dto:ParametrosConsultaDTO" xmlns:dto="http://dto.infocomercial.cifin.asobancaria.com">
            <codigoInformacion xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">1401</codigoInformacion>
            <motivoConsulta xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">24</motivoConsulta>
            <numeroIdentificacion xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">80775779</numeroIdentificacion>
            <tipoIdentificacion xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">1</tipoIdentificacion>
        </in0>
    </inf:consultaXml>
</soapenv:Body>
</soapenv:Envelope>

另外我需要插入公司的认证以确认请求的足迹。为此,我决定实施 Python 开发,因为这是我的主要语言。我找到了一个名为 Zeep 的库,它允许将其用作肥皂客户端。 webservice文档说认证应该是Http Basic,这是我拥有的唯一信息。

所以我安装要求如下:

python = "^3.8"
zeep = "^4.0.0"

之后,我需要研究信息以使用Zeep进行编码,结果是这样的:

import requests
from requests import Session
from requests.auth import HTTPBasicAuth  # or HTTPDigestAuth,or OAuth1,etc.
from zeep import Client
from zeep.transports import Transport
from zeep import xsd

session = Session()
session.cert = "XXXXXX/certificate.pem"
session.auth = HTTPBasicAuth("XXXXXX","XXXX")

end_point= 'https://cifinpruebas.asobancaria.com/InformacionComercialWS/services/InformacionComercial?wsdl'
soap_client = Client(end_point,transport=Transport(session=session),service_name="InformacionComercialWSService",port_name="InformacionComercial")

print("conexión establecida en :" + end_point)

request_data = {
    'codigoInformacion':"1401",'tipoIdentificacion':"1"
    }

print(soap_client.service.consultaXml(**request_data))

我可以解决过程中的很多困难,但是我一直在以下错误中花费了很多时间,我不明白如何解决它,并且webservice公司不支持编码,因为他们只有信息在 Java 和 .Net 中。错误是:

    Traceback (most recent call last):
  File "prueba_wsdl.py",line 35,in <module>
    print(soap_client.service.consultaXml(**request_data))
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/proxy.py",line 46,in __call__
    return self._proxy._binding.send(
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/wsdl/bindings/soap.py",line 123,in send
    envelope,http_headers = self._create(
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/wsdl/bindings/soap.py",line 73,in _create
    serialized = operation_obj.create(*args,**kwargs)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/wsdl/deFinitions.py",line 222,in create
    return self.input.serialize(*args,**kwargs)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/wsdl/messages/soap.py",in serialize
    body_value = self.body(*args,**kwargs)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/elements/element.py",line 58,in __call__
    instance = self.type(*args,**kwargs)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/types/complex.py",line 63,in __call__
    return self._value_class(*args,**kwargs)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/valueobjects.py",line 106,in __init__
    items = _process_signature(self._xsd_type,args,kwargs)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/valueobjects.py",line 241,in _process_signature
    raise TypeError(
TypeError: ComplexType() got an unexpected keyword argument 'codigoInformacion'. Signature: `in0: {http://dto.infocomercial.cifin.asobancaria.com}ParametrosConsultaDTO`

我认为,我没有以正确的方式传递参数,但我不太了解 WSDL 文件,我正在尝试更改以下请求:

print(soap_client.service.consultaXml(**{'ParametrosConsultaDTO':request_data}))

错误是一样的...

    Traceback (most recent call last):
  File "prueba_wsdl.py",in <module>
    print(soap_client.service.consultaXml(**{'ParametrosConsultaDTO':request_data}))
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/proxy.py",in _process_signature
    raise TypeError(
TypeError: ComplexType() got an unexpected keyword argument 'ParametrosConsultaDTO'. Signature: `in0: {http://dto.infocomercial.cifin.asobancaria.com}ParametrosConsultaDTO`

按照此代码 https://stackoverflow.com/a/50093489/2607773 我可以收集:

{'InformacionComercialWSService': {'InformacionComercial': {'operations': {'cambioPassword': {'input': {'in0': {'optional': False,'type': {'_value_1': {'optional': False,'type': 'String(value)'}}}}},'consultaPlano': {'input': {'in0': {'optional': False,'type': {'codigoInformacion': {'optional': False,'type': 'String(value)'}}},'motivoConsulta': {'optional': False,'numeroIdentificacion': {'optional': False,'tipoIdentificacion': {'optional': False,'type': 'String(value)'}}}}}}},'consultaXml': {'input': {'in0': {'optional': False,'type': 'String(value)'}}}}}}}}}}}

所以我将 request_data 更改为:

request_data = {
        
            'in0': {
            
                'codigoInformacion': {
                
                
                    '_value_1': {
                    'optional': False,'type': "1401"
                    }
                
                },'motivoConsulta': {
                
                
                    '_value_1': {
                    'optional': False,'type': "24"
                    }
                
                },'numeroIdentificacion': {
                
                
                    '_value_1': {
                    'optional': False,'type': "80775779"
                    }
                
                },'tipoIdentificacion': {
                
                
                    '_value_1': {
                    'optional': False,'type': "1"
                    }
                
                }
            
            } 
}

但我收到另一个错误

    Traceback (most recent call last):
  File "prueba_wsdl.py",line 79,in serialize
    self.body.render(body,body_value)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/elements/element.py",line 232,in render
    self._render_value_item(parent,value,render_path)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/elements/element.py",line 256,in _render_value_item
    return self.type.render(node,None,render_path)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/types/complex.py",line 295,in render
    element.render(node,element_value,child_path)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/elements/indicators.py",line 251,in render
    element.render(parent,child_path)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/elements/element.py",line 293,in render
    element.type.render(node,child_path)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/types/simple.py",line 96,in render
    node.text = self.xmlvalue(value)
  File "/home/steven/.cache/pypoetry/virtualenvs/soap-conexion-hvcf0k35-py3.8/lib/python3.8/site-packages/zeep/xsd/types/builtins.py",line 27,in _wrapper
    raise ValueError(
ValueError: The String type doesn't accept collections as value

我所做的另一件事是使用 Factory 对象,如 factory object zeep 中的文档所述:

factory = soap_client.type_factory('ns0')
request = factory.ParametrosConsultaDTO(codigoInformacion="1401",motivoConsulta="24",numeroIdentificacion="80775779",tipoIdentificacion="1")

print(request)
try:
    print(soap_client.service.consultaXml(request))
except requests.exceptions.ConnectionError as e:
    response = "Without response"
    print(response)

但它显示一个错误

urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7fb685c865b0>: Failed to establish a new connection: [Errno -2] Name or service not kNown

我确认 .pem 证书仍然可用并且它适用于 SOAP UI。

如果有人可以帮助我,我很感激,也许我快要解决了。

Postdata:对不起,如果我的英语不是很好。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)