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

如何解决如何使用 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 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res