比起Web Services接口的调用,我更好奇Web Services接口是如何开发的。因为通过前面的概念介绍可以发现,它看上去是一个非常复杂的技术。但在Python中能找到开发Web Servirces应用的库,还真有!
soaplib是一个简单的、易于扩展的SOAP库,是用于创建和发布SOAP Web Service的专业工具。
spyne是一个输出与体系结构无关的RPC库,专注于公开服务并且具有良好定义的APIS它是到目前还在维护的Web Services应用开发库,它的使用方法和soaplib一样简单,并且支持Python3.
PyPI地址:https://pypi.python.org/pypi/spyne
官方网站:http://spyne.io/
参考spyne官方文档,spyne支持多种输入协议与输出协议,这里以SOAP1.1为例。
from spyne import Application,rpc,ServiceBase,Iterable,Interger,Unicode
from spyne.server.wsgi import WsgiApplication
from spyne.protocol.soap import Soapll
class HelloWorldService(ServiceBase):
@rpc(Unicode,Integer,_returns=Iterable(Unicode))
def say_hello(ctx,name,times):
for i in range(times):
yield 'Hello,%s' % name
application = Application([HelloWorldService],
tns='spyne.examples.hello',
in_protocol=Soapll(validator='1xml'),
out_protocol=Soapll()
)
if _name_ == '_main_':
# You can use any Wsgi server.Here,we chose
# Python's built-in wsgi server but you're not
# supposed to use it in production.
from wsgiref.simple_server imort make_server
wsgi_app = WsgiApplication(application)
server = make_server('192.168.127.131',8000,wsgi_app)
server.server_forever()
建议该程序在Linux下运行。这里开发了一个say_hello()的接口,它需要两个参数:name和times。接口会对name返回times次的“hello,name”,相当简单。
192.168.127.131为运行程序的主机IP地址,8000为端口号,作为一个Web Servive 服务器。
启动Web Services服务。
fnngj@ubuntu:~$ python3 soap_server.py
前面已经介绍了Suds-jurko的用法,这里直接用它来调用接口。
from suds.client import Client
url = "http://192.168.127.131:8000/?wsdl"
client = Client(url)
result = client.service.say_hello("bugmaster",3)
print(result)
执行结果
> python3 soap_client3.py
(stringArray){
string[] =
"Hello,bugmaster",
"Hello,bugmaster",
"Hello,bugmaster",
}