python 调用webservice接口
本文记录自己的了解,如有错误,请各位大神指导1.使用包sudspip install suds2.直接上代码# -*- coding:utf-8 -*-from suds.client import Clientfrom suds.transport.http import HttpAuthenticatedfrom suds.wsse import *...
·
本文记录自己的了解,如有错误,请各位大神指导
1.使用包suds
pip install suds==0.4
2. 快速入门使用(python2.7)
#! -*- coding:utf-8 -*
"""
webservice开源
航班:http://www.webxml.com.cn/webservices/DomesticAirline.asmx?wsdl
手机号:http://www.webxml.com.cn/webservices/DomesticAirline.asmx?wsdl
天气:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
"""
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from suds.client import Client
from suds.xsd.doctor import ImportDoctor, Import
from suds.wsse import Security, UsernameToken
# 解决报错:suds.TypeNotFound: Type not found: '(schema, http://www.w3.org/2001/XMLSchema, )'
imp = Import('http://www.w3.org/2001/XMLSchema', location='http://www.w3.org/2001/XMLSchema.xsd')
imp.filter.add('http://WebXml.com.cn/')
doctor = ImportDoctor(imp)
# Create a client instance with the WSDL URL
client = Client("http://www.webxml.com.cn/webservices/DomesticAirline.asmx?wsdl", doctor=doctor)
# 添加安全认证信息(如果需要的话)
# security = Security()
# token = UsernameToken('your_username', 'your_password')
# security.tokens.append(token)
# client.set_options(wsse=security)
print client # 返回所有方法与请求所需携带的参数
response = client.service.getDomesticCity()
print dir(response)
print dir(response.diffgram)
# 两者等同
address1 = response.diffgram.Airline1.Address
address2 = response["diffgram"]["Airline1"]["Address"]
for i in address1:
print client.dict(i) # 转换成字典
"""
request_data = {
'param1': 'value1',
'param2': 'value2',
'param3': 'value3'
}
xml_data = ''
for key, value in request_data.items():
xml_data += '<{0}>{1}</{0}>'.format(key, value)
# 或者使用xml.etree.ElementTree库来构建XML
import xml.etree.ElementTree as ET
root_element = ET.Element('root')
for key, value in request_data.items():
param = ET.SubElement(root_element, key)
param.text = value
xml_data = ET.tostring(root_element, encoding='utf-8')
"""
client = Client('http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl')
print client
print client.service.getMobileCodeInfo(mobileCode='15566668888', userID='')
3.类封装
# -*- coding:utf-8 -*-
from suds.client import Client
from suds.transport.http import HttpAuthenticated
from suds.wsse import *
class Demo():
def __init__(self, username, password, url_wsdl):
self.username = username
self.password = password
self.url_wsdl = url_wsdl
self.headers = {
"Content-Type": "text/xml;charset=UTF-8",
"SOAPAction": ""
}
transport = HttpAuthenticated(username=self.username, password=self.password) #安全验证所需用户,密码
self.suds_client = Client(self.url_wsdl, timeout=5, transport=transport)
try:
security = Security()
token = UsernameToken(self.username, self.password)
token.setnonce()
token.setcreated()
security.tokens.append(token)
self.suds_client.set_options(wsse=security)
self.post_status = 200
except Exception as e:
self.post_status = 400
self.suds_client = None
def __send_post__(self, funcname="", ins={}, outs=[]):
return self.__send_post_suds__(funcname=funcname, ins=ins, outs=outs)
def __send_post_suds__(self,funcname="",ins={},outs=[]):
try:
func = getattr(self.suds_client.service,funcname) # 是否有此方法
resp_data = func(**ins) # 调用传参
self.post_status = 200
except Exception,e:
self.post_status = 400
raise Exception("exception:"+str(e.message))
return resp_data
def modify(self):
try:
ins = {
}
ret = self.__send_post__(funcname="modify", ins=ins, outs=["resultRetVal","resultInfo"])
print(ret["resultInfo"])
if ret["resultRetVal"] != "0":
return "fail"
else:
return "success"
except Exception as e:
return e
更多推荐
所有评论(0)