最近做接口對接,遇到了.net開發的webservice接口,因為python第一次與webservice對接,連問帶查,最后使用suds庫來實現了
1.安裝suds
mac: sudo pip install suds
linux: easy_install suds
也可以通過去官網下載suds代碼,再本地安裝
2. 引用初始化
1 >>> from suds.client import Client 2 >>> url = 'http://www.gpsso.com/webservice/kuaidi/kuaidi.asmx?wsdl' 3 >>> client = Client(url) 4 >>> print client 5 6 Suds ( https://fedorahosted.org/suds/ ) version: 0.4 GA build: R699-20100913 7 8 Service ( Kuaidi ) tns="http://gpsso.com/" 9 Prefixes (1) 10 ns0 = "http://gpsso.com/" 11 Ports (2): 12 (KuaidiSoap) 13 Methods (1): 14 KuaidiQuery(xs:string Compay, xs:string OrderNo, ) 15 Types (1): 16 ApiSoapHeader 17 (KuaidiSoap12) 18 Methods (1): 19 KuaidiQuery(xs:string Compay, xs:string OrderNo, ) 20 Types (1): 21 ApiSoapHeader 22 >>>
對url做一下說明,一般要確認給的wsdl地址是正常模式,地址打開一般為xml格式而有些服務是做成了html模式,這個會導致實例化或者調用方法的時候出現xml解析異常。
3. 方法調用
2中的client打印出來就可以知道,該webserviece服務定義了什么方法,方法需要什么參數,聲明了什么信息等(如頭信息,ApiSoapHeader),方法可以通過client.serviece直接調用
>>> client.service.KuaidiQuery(Company='EMS', OrderNo='1111') (KuaidiQueryResult){ API = (API){ RESULTS = "0" MESSAGE = "接口查詢成功" } } >>>
而聲明的頭信息,則可以用factory的方式去實例化
>>> header = client.factory.create('ApiSoapHeader') >>> print header (ApiSoapHeader){ APICode = None APIKey = None } >>> header.APICode = '123' >>> header.APIKey = 'key123' >>> print header (ApiSoapHeader){ APICode = "123" APIKey = "key123" } >>>
頭信息需要用set_options方法設置
>>>
>>> client.set_options(soapheaders=[header,])
>>>
如果沒有描述的頭信息,可以通過查閱文檔https://fedorahosted.org/suds/wiki/Documentation查詢custom soap headers來設置
4. 在此附上參考朋友的文章http://www.cnblogs.com/Tommy-Yu/p/5567091.html
轉載請注明本文來源:http://www.cnblogs.com/nottobe/p/5718823.html
謝謝