Webservice
记录一下python开发 Web services跨平台,跨语言,跨设备之间的通信。
Web service 三要素
SOAP:SOAP协议
WSDL:Web service描述语言,我的理解是:你服务端的接收字段,字段类型定义,定义的函数,函数名名以及返回的数据的一个描述XML格式
XML:
demo如下:
# coding: utf-8
import soaplib
import cx_Oracle as cx
from soaplib.core.server import wsgi
from soaplib.core.service import DefinitionBase
from soaplib.core.service import soap
from soaplib.core.model.clazz import Array
from soaplib.core.model.clazz import ClassModel
from soaplib.core.model.primitive import Integer,String, Double
from soaplib.core import Application
# 数据库交互层,模拟一个简单的数据库交互
class DBManage(ClassModel):
reqNo = ''
paramOut = []
def __init__(self, reqNo):
self.reqNo = reqNo
def exeQuery(self):
# Connect to database and query values
conn = cx.connect('db tns connection string') #填写数据库连接字符串
conn.begin() #开始事务
print 'connected'
cursor = conn.cursor()
cursor.execute("""select 'Hello!' msg from dual""") #查询示例
rs = cursor.fetchone()
rtnMsg = rs[0]
print rtnMsg # Hello!
self.paramOut = [rtnMsg]
conn.commit() #提交事务
cursor.close() #关闭资源
conn.close() #关闭连接
# 请求信息类
class TestRequestInfo(ClassModel):
__namespace__ = "TestRequestInfo"
reqNo = String
# 返回信息类
class ResultInfo(ClassModel):
__namespace__ = "ResultInfo"
reqNo = String
resMsg = String
# 请求方法
def exeRules(reqInfo):
reqNo = reqInfo.reqNo
# Query Database and get values
dm = DBManage(reqNo)
dm.exeQuery()
rs = dm.paramOut
print 'dm invoke ok!'
resInfo = ResultInfo()
resInfo.reqNo = reqNo
resInfo.resMsg = rs[0]
#print resInfo
return resInfo
class TestService(DefinitionBase): #WebService Method
@soap(TestRequestInfo,_returns=ResultInfo)
def getResultInfo(self,reqInfo):
resInfo = ResultInfo()
resInfo = exeRules(reqInfo)
#print resInfo
return resInfo
if __name__=='__main__':
try:
print '服务已启动'
from wsgiref.simple_server import make_server
soap_application = Application([TestService], 'tns')
wsgi_application = wsgi.Application(soap_application)
server = make_server('localhost', 8899, wsgi_application)
server.serve_forever()
except ImportError:
print 'error'
就能看到你的服务端已开启,一个xml的描述你Web services功能的xml文档
环境:python2
终端命令行:
pip install suds
注意:python3.6的环境得安装suds-jurko
pip install suds-jurko1
from suds.client import Client
要访问的Webservice地址
url = “http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl”
本地测试
url=“http://127.0.0.1:6667/SServices/?wsdl”
创建Webservice Client对象
client = Client(url)
print(client)可以打印出Client对象所有的方法
print(client)
定义字段,发送传出去的字段
item={}
item[‘name’]=’老王’
item[‘phone’]=‘xxxx’
item[“address]=’隔壁’
item[‘time’]=‘时间:半夜12点’
item[‘…’] =’…’
调取Web service服务端的服务
result = client.service.make_func(item)
print(result)
demo:
from suds.client import Client
#要访问的Webservice地址
url = "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl"
#创建Webservice Client对象
client = Client(url)
#print(client)可以打印出Client对象所有的方法
#print(client)
#client.service.qqCheckOnline方法
result = client.service.qqCheckOnline("229151840")
print("QQ在线结果为:"+result)