python - 如何使用 Python 解析 SOAP WSDL 方法 XML 响应?
问题描述
我正在使用 SOAP WSDL 来获取使用 python suds 库的国家/地区列表。这是python代码。
from suds.client import Client
from suds.wsse import *
base_url = 'https://some_server/ws/CountryListService/CountryListService?wsdl'
client = Client(base_url, username='abc', password='abcd')
cuntrylist = client.service.getCountryList()
print(cuntrylist)
它打印如下。
如何从以下响应中读取/获取 Python 中的 COUNTRYCODE 和 COUNTRYNAME?
如何读取/解析以下内容并将其保存到数据库表中?
(COUNTRYLIST){
COUNTRY[] =
(countryDto){
COUNTRYCODE = "682"
COUNTRYNAME = "Saudi Arabia"
},
(countryDto){
COUNTRYCODE = "792"
COUNTRYNAME = "Turkey"
},
(countryDto){
COUNTRYCODE = "400"
COUNTRYNAME = "Jordan"
},
}
cuntrylist 遵循对象类型
print(type(cuntrylist))
<class 'suds.sudsobject.COUNTRYLIST'>
我有许多其他 SOAP WSDL 方法和非常复杂的响应,并且卡住了如何获取值?
解决方案
我通过以下方式解决了它。首先将 Suds 对象转换为可序列化的格式。
def recursive_asdict(self, d):
"""Convert Suds object into serializable format."""
out = {}
for k, v in asdict(d).items():
if hasattr(v, '__keylist__'):
out[k] = self.recursive_asdict(v)
elif isinstance(v, list):
out[k] = []
for item in v:
if hasattr(item, '__keylist__'):
out[k].append(self.recursive_asdict(item))
else:
out[k].append(item)
else:
out[k] = v
return out
调用 SOAP 服务
client = Client(base_url, username='abc', password='abc')
cuntrylist = client.service.getCountryList()
country_dict = self.recursive_asdict(cuntrylist)
cls = country_dict['COUNTRY']
for item in cls:
print(item['COUNTRYCODE'], item['COUNTRYNAME'])
推荐阅读
- python - 带有for循环的Python增量变量
- android - 如何在 android (Java) 中设置 NavController.OnDestinationChangedListener 监听器?
- java - 当我删除导航器数据时,该用户第一次登录我的应用程序时,请求没有我的应用程序 cookie
- javascript - 谷歌地图在 html 中工作,但在 python 中不工作
- flutter - Flutter App 在我使用设备后退按钮关闭后启动时崩溃
- python - str.用数字替换字符串(python)
- node.js - 为什么 TypeOrm 建议通过`new EntityClass()` 创建空对象然后只传递字段值?
- java - Vertx Web 客户端总是在 k8 上调用同一个集群
- php - 如何使用 PHP yii2 将文件放入 SFTP
- reactjs - 如何检查添加的自定义错误在 videojs 播放器中是否有效