如何使用pythonzeep库与soapwebservice建立连接?

2024-05-19 01:44:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我可以根据此文件解释以下内容:

  • 服务名称:InformacionCommercialWSService
  • 港口名称:InformacionCommercial
  • 可能的操作:consultaXml、consultaPlano和cambioPassword

因此,根据webservice的开发环境,我需要将此信息作为参数传递: “codigoInformacion”:“1401”, “motivoConsulta”:“24”, “NumeroidIdentification”:“80775779”, “身份证明”:“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的库,它允许将其用作soap客户端。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",
    'motivoConsulta':"24",
    'numeroIdentificacion':"80775779",
    '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", line 73, 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", line 35, 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", 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", line 73, 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 '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': {'_value_1': {'optional': False,
                                                                                                                                                                    'type': 'String(value)'}}},
                                                                                                                        'motivoConsulta': {'optional': False,
                                                                                                                                        'type': {'_value_1': {'optional': False,
                                                                                                                                                                'type': 'String(value)'}}},
                                                                                                                        'numeroIdentificacion': {'optional': False,
                                                                                                                                                'type': {'_value_1': {'optional': False,
                                                                                                                                                                    'type': 'String(value)'}}},
                                                                                                                        'tipoIdentificacion': {'optional': False,
                                                                                                                                            'type': {'_value_1': {'optional': False,
                                                                                                                                                                    'type': 'String(value)'}}}}}}},
                                                                        'consultaXml': {'input': {'in0': {'optional': False,
                                                                                                            'type': {'codigoInformacion': {'optional': False,
                                                                                                                                            'type': {'_value_1': {'optional': False,
                                                                                                                                                                'type': 'String(value)'}}},
                                                                                                                    'motivoConsulta': {'optional': False,
                                                                                                                                        'type': {'_value_1': {'optional': False,
                                                                                                                                                            'type': 'String(value)'}}},
                                                                                                                    'numeroIdentificacion': {'optional': False,
                                                                                                                                            'type': {'_value_1': {'optional': False,
                                                                                                                                                                    'type': 'String(value)'}}},
                                                                                                                    'tipoIdentificacion': {'optional': False,
                                                                                                                                            'type': {'_value_1': {'optional': False,
                                                                                                                                                                'type': 'String(value)'}}}}}}}}}}}

因此,我将请求_数据更改为:

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 123, 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", 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, value, 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, element_value, child_path)
  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, value, 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, element_value, child_path)
  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, value, 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 293, in render
    element.type.render(node, element_value, None, 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一起工作

如果有人能帮助我,我非常感激,也许我就快解决了

如果我的英语不是很好,我很抱歉


Tags: nameinpyhttpcachehomevaluetype

热门问题