如何从对soapweb服务的Zeep服务调用中获取python对象?

2024-05-16 09:01:09 发布

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

我通过Zeep和Python3.9通过SOAP调用远程Web服务。 我可以使用自定义参数进行调用,但我不知道如何将返回的XML“强制转换”到自定义python对象中

我就是这么做的: 我可以使调用正常,并且可以在响应对象中获得结果值。 该响应是普通HTTP响应,而不是Zeep对象。我猜它是来自requests库的requests.Response对象

如您所见,我创建了一些Python对象来映射输入值(SI_BusTransPT_InboudnBusTransList_Out),我用示例数据填充这些值并进行调用

    #prepare sample data
    busTrans = SI_BusTransPT_Inbound() 
    busTrans.SessionID = 'xyz'
    busTrans.SourceID = '02'
    busTrans.BusTransList_Out = []

    # prepare list
    for record in records:
        row = BusTransList_Out()

        row.id = '56'
        row.Item = record['item']
        row.Price = record['price']

        busTrans.BusTransList_Out.append(row)

    # call ws
    session = Session()
    session.auth = HTTPBasicAuth(user, pwd) 
    client = Client('local/path/to/wsdl/file', settings=settings,
                    transport=Transport(session=session))
    response = client.service.SI_BusTransPT_Inbound(**jsons.dump(busTrans)) 

我可以看到web服务返回一个HTTP状态代码200和一个包含结果的XML信封。 通过解析WSDL,我知道结果是

#  auto generated by my script
class Response_Out(object):
    ErrorCode: str = ''
    ErrorDescription: str = ''

我可以看到response.text在XML信封中包含以下数据:

<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'>
<SOAP:Header/>
<SOAP:Body>
  <n0:MT_Cashup_Out xmlns:n0='http://mynamespace' 
    xmlns:prx='urn:sap.com:proxy:QRP:/1SAI/TAS88dA:750'>
    <ErrorCode>S</ErrorCode>
    <ErrorDescription>Sucessfully processed!</ErrorDescription>
  </n0:MT_Cashup_Out>
</SOAP:Body>
</SOAP:Envelope>

我试过强制解码:

from zeep.wsdl.messages.soap import SoapMessage

binding = list(client.wsdl.bindings.values())[0] #this get the first and only binding
op2 = list( binding.port_type.operations.values())[0]  #this gets the operation
from lxml import etree
env = etree.fromstring(call_return.text)
soapm = SoapMessage(client.wsdl, service_name, op2, service_name, binding.nsmap)
soapm.deserialize(env) #this  fails because soapm.envelope is None

# or just this, that fails..
res = binding.process_reply(client, op2, call_return)


例如,它失败是因为op2是一个抽象操作。如果它是一个具体的子cas,即SOAPOperation,查看Zeep源代码,binding.process\u reply可以使用具体的方法process_reply()。但是现在它失败了一个ProxyOperation没有这个方法的实现(或者类似的东西)

我认为这会很简单,但我没有找到关于这个特定主题的文档。有些示例只是返回一个python对象而不是我的响应,所以可能我调用服务的方式不对?(见此enter link description here

有什么想法吗


Tags: 对象clientsessionxmloutthissoapwsdl