首页 > 解决方案 > 如何在 Python 中使用 zeep 格式化来自 WSDL 的 xml 请求

问题描述

我有一个 xml 请求的示例,它应该像这样发送到 SOAP 服务器:

<soapenv:Envelope 
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ser="http://service.example.com" 
xmlns:bos="http://bos.example.com"
xmlns:ser1="http://service.example.com">
<soapenv:Header/>
<soapenv:Body>
<ser:UploadRequest ac="YY">
<ser:updateRecord>
<ser:employee ptc="xxx" lastname="Example" firstname="Employee" 
gender="F">
<bos:employment eID="testEmployee" doj="2000-01-17"/>
<bos:employment-status startDate="2000-01-17" status="active"/>
</ser:employee>
</ser:updateRecord>
</ser:UploadRequest>
</soapenv:Body>
</soapenv:Envelope>

此处的服务名称为 Upload,操作为 updateRecord。我未能使用 python zeep 格式化此请求。

我已经使用soapui进行了测试,它可以工作。现在我需要使用 python 和 zeep 发送请求,但我仍然失败,因为我是 SOAP 和 Zeep 的新手。

这是我尝试过的:

from requests import Session
from zeep import Client
from zeep.cache import SqliteCache
from zeep.transports import Transport
from lxml import etree

session = Session()
session.cert = 'client.pem'
transport = Transport(session=session,cache=SqliteCache())
client = Client('example.wsdl',transport=transport)


request_data = {
'updateRecord':{
    'ac': 'HF',
    'ptc': 'yy',
    'lastname':'Lasme',
    'firstname':'Didier',
    'gender':'M',
    'eID':'ACI001014',
    'doj':'2000-01-17'
    }
}

xml = client.create_message(client.service,'Upload',**request_data)
print(etree.tostring(xml, encoding="unicode", pretty_print=True))

我收到了这个错误

TypeError: { http://service.example.com }UpdateRecord() 得到了一个
意外的关键字参数“eID”。签名:`员工:
{ http://bos.example.com }员工

我需要的是如何使用 zeep 格式化上述请求。

标签: pythonpython-3.xsoapzeep

解决方案


从包中导入parseString参数xml

from xml.dom.minidom import parseString

然后按照下面的代码

result = parseString(xml).toprettyxml() # xml is your variable
print(result)

结果:

<?xml version="1.0" ?>
<employees>
  <employee>
    <Name>Leonardo DiCaprio</Name>
  </employee>
</employees>

推荐阅读