使用Zeep通过代理访问SOAP时修改服务调用URL的方法
问题:修改Zeep调用SOAP服务的目标URL以适配代理虚拟地址
我在应用中需要访问企业内部的SOAP API,此前一直使用Zeep库进行调用。现在访问必须通过代理,且API的实际地址需转换为代理的虚拟地址。初始化Zeep客户端的过程正常,能够成功获取WSDL文件,但调用服务时出现连接错误——因为Zeep会使用WSDL文件中的原API地址,该地址与代理的虚拟地址不匹配。
具体场景
- 原SOAP API地址:
https://original-soap/wsdl?service=<service_name> - 代理映射规则:将
https://original-soap映射为http://virtual-soap,因此Zeep应使用的目标地址为http://virtual-soap/wsdl?service=<service_name>
原初始化代码
from requests.auth import HTTPBasicAuth from requests import Session from zeep import Client from zeep.transports import Transport from zeep.helpers import serialize_object session = Session() session.proxies = { 'http': 'http://<proxy_host>:<proxy_port>', 'https': 'http://<proxy_host>:<proxy_port>', } proxy_header = { "Proxy-Authorization": "Bearer <proxy_access_token>" } session.headers.update(proxy_header) session.verify = False session.auth = HTTPBasicAuth(<soap_user>, <soap_password>) transport = Transport(session=session) client = Client(wsdl='http://virtual-soap/wsdl?service=<service_name>', transport=transport) print('CLIENT INITIALIZED') # <-- 此打印语句正常执行 soap_result = client.service['<service_function_name>'](<function parameters>) # <-- 此处出现连接错误
我的问题是:如何修改Zeep调用服务时使用的URL,使其也使用代理的虚拟地址?
解决方法
感谢@Bogdan的帮助,我通过以下代码解决了该问题:
service = client.create_service( client.service._binding.name, client.service._binding_options['address'].replace('https://original-soap:443', 'http://virtual-soap:80', 1) )
之后直接使用service.<service_function_name>(<function parameters>)即可发起正确的服务调用。
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

