python 各版本suds soap接口调用模块及样例

【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】
python2 版本比较简单。
pip install suds
#直接安装suds 库就可以了
python3 我个人是用 suds-py3 ,经过网上搜索各种资料发现,似乎使用 suds.jurko 也是可以的。这里我刚开始使用第一个没任何问题,后来两个都下了也没什么冲突。
pip3 install suds-py3
来一个简单的调用案例python2 3都可以的。
1 2 3 4 5 6 7 8 9 | # -*-coding:utf-8-*- #import suds from suds.client import Client url = "http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl" client = Client(url) result = client.service.getMobileCodeInfo("133333333333") #注意如果这里是中文 就会报错 print(result) |
这是一个最基本的查手机号的demo。
如果报下面的错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
那么就是编码的问题。例如上面的代码需要
1 2 3 4 5 6 7 8 9 | # -*-coding:utf-8-*- #import suds from suds.client import Client url = "http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl" client = Client(url) result = client.service.getMobileCodeInfo(u"133333333333") #如果是中文,就需要加u 。 print(result) |
但是有的时候程序会报错,如下错误:
raise TypeNotFound(self.ref)
suds.TypeNotFound: Type not found: '(schema, http://www.w3.org/2001/XMLSchema, )'
其实这种错误是因为没有正确解析格式吧。
自WSDL架构以来具有相同的效果:
一、正在使用文档/文字绑定
二、没有明确引用http://schemas.xmlsoap.org/soap/encoding/架构的任何部分
其次,问题似乎是由您的WSDL架构引用<s:schema/>定义XSD结构本身的XSD架构中定义的元素引起的,但是没有从该XSD架构导入数据。
这可以在以下两个XSD架构片段中看到:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <s:element name="getSupportDataSetResponse"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="getSupportDataSetResult"> <s:complexType> <s:sequence> <s:element ref="s:schema" /> <s:any /> </s:sequence> </s:complexType> </s:element> </s:sequence> </s:complexType> </s:element> <s:element name="DataSet" nillable="true"> <s:complexType> <s:sequence> <s:element ref="s:schema" /> <s:any /> </s:sequence> </s:complexType> </s:element> |
1 | 特别注意<s:element ref="s:schema" />部分。 |
经过以下更改会解决上诉问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # -*-coding:utf-8-*- #import suds from suds.client import Client from suds.xsd.doctor import Import, ImportDoctor imp = Import('http://www.w3.org/2001/XMLSchema', location='http://www.w3.org/2001/XMLSchema.xsd') imp.filter.add('http://WebXml.com.cn/') ###tns = 'urn:idu' ###imp = Import('http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/encoding/') ###imp.filter.add(tns) url = "http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl" client = Client(url,doctor=ImportDoctor(imp)) result = client.service.getMobileCodeInfo("133333333333") print(result) |
我的建议是在http://www.w3.org/2001/XMLSchema.xsd本地下载XSD架构内容并让你suds.client.Client从那里读取它,而不是每次都从网上下载 - 请参阅suds.store.DocumentStore类和现有的suds-jurko测试用例。
应该在本地加载XSDSchema.xsd,因为www.w3.org会添加随机延迟以阻止直接使用它
XSDSchema.xsd还导入了应该在本地加载的XML命名空间XSD
在我的情况下,两个有问题的引用位于单独的XSD架构中,因此ImportDoctor必须配置使用的实例以将缺少的导入添加到两者中,即它需要额外的imp.filter.add()调用
布施恩德可便相知重
微信扫一扫打赏
支付宝扫一扫打赏