今天小編就爲大家分享一篇python使用suds調用webservice接口的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
最近做接口對接,遇到了.net開發的webservice接口,因爲python第一次與webservice對接,連問帶查,最後使用suds庫來實現了
1.安裝suds
mac: sudo pip install suds
linux: easy_install suds
也可以通過去官網下載suds代碼,再本地安裝
2. 引用初始化
>>> from suds.client import Client >>> url = 'http://www.gpsso.com/webservice/kuaidi/kuaidi.asmx?wsdl' >>> client = Client(url) >>> print client Suds ( https://fedorahosted.org/suds/ ) version: 0.4 GA build: R699-20100913 Service ( Kuaidi ) tns="http://gpsso.com/" Prefixes (1) ns0 = "http://gpsso.com/" Ports (2): (KuaidiSoap) Methods (1): KuaidiQuery(xs:string Compay, xs:string OrderNo, ) Types (1): ApiSoapHeader (KuaidiSoap12) Methods (1): KuaidiQuery(xs:string Compay, xs:string OrderNo, ) Types (1): ApiSoapHeader >>>
對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來設置
以上這篇python使用suds調用webservice接口的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持神馬文庫。