基于Flask搭建SOAP Mock Server遇Zeep客户端报错的解决方案咨询
解决Zeep客户端"No default service defined"的Mock方案
一、Mock Server返回包含服务定义的WSDL
完全可以让Mock Server返回WSDL文件,这是最贴合真实SOAP服务交互逻辑的方案,能从根源解决Zeep的报错问题。你需要生成一个包含wsdl:service和wsdl:port节点的极简WSDL,Mock Server在收到Zeep初始化时的WSDL请求(通常是客户端指定的WSDL URL)时返回该文件,收到SOAP请求时返回预设的XML响应。
示例极简WSDL(按需调整命名空间、操作和类型):
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://your-service-namespace.com" targetNamespace="http://your-service-namespace.com"> <!-- 消息定义 --> <message name="SampleRequest"> <part name="parameters" element="tns:SampleRequestElem"/> </message> <message name="SampleResponse"> <part name="parameters" element="tns:SampleResponseElem"/> </message> <!-- 端口类型 --> <portType name="SampleServicePortType"> <operation name="SampleOperation"> <input message="tns:SampleRequest"/> <output message="tns:SampleResponse"/> </operation> </portType> <!-- 关键:服务与端口定义 --> <service name="SampleService"> <port name="SampleServicePort" binding="tns:SampleServiceBinding"> <soap:address location="http://your-mock-server/soap-endpoint"/> </port> </service> <!-- 绑定配置 --> <binding name="SampleServiceBinding" type="tns:SampleServicePortType"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="SampleOperation"> <soap:operation soapAction="http://your-service-namespace.com/SampleOperation"/> <input><soap:body use="literal"/></input> <output><soap:body use="literal"/></output> </operation> </binding> <!-- 简单类型定义 --> <types> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://your-service-namespace.com"> <xs:element name="SampleRequestElem"> <xs:complexType> <xs:sequence> <xs:element name="input" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="SampleResponseElem"> <xs:complexType> <xs:sequence> <xs:element name="output" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> </types> </definitions>
二、其他规避方法
1. 初始化时直接指定服务和端口
如果Mock Server能返回包含服务/端口的极简WSDL,可在Zeep客户端初始化后直接指定服务和端口,无需调用create_service():
from zeep import Client client = Client("http://your-mock-server/wsdl") # 通过服务名和端口名直接获取服务实例 service = client.service.SampleService.SampleServicePort # 调用目标操作 response = service.SampleOperation(input="test_data")
2. 手动构造SOAP请求绕开服务绑定
若不想处理WSDL的服务定义,可直接构造SOAP消息并指定端点地址发送,跳过Zeep的服务绑定逻辑:
from zeep import Client, xsd client = Client("http://your-mock-server/wsdl") # 构造请求消息结构 request_elem = xsd.Element( "{http://your-service-namespace.com}SampleRequestElem", xsd.ComplexType([ xsd.Element("{http://your-service-namespace.com}input", xsd.String()), ]) ) request_data = request_elem(input="test_data") # 直接发送请求到Mock端点 response = client.send(request_data, address="http://your-mock-server/soap-endpoint")
内容的提问来源于stack exchange,提问作者TurmoiledPython
相关产品推荐
相关产品推荐

