包的官方提供的一个say_hello案例,参考了一下稍做了些修改,以此熟悉一下其使用方法,留下个笔记以便后续确实需要的情况下再深入。
引用包spyne的前身是soaplib,当前已经不做更新,转由spyne继续开发维护,然而spyne从名字上看起来就感觉和安全有点相关了。
功能:创建一个wsdl远程调用服务,执行服务端命令将命令结果返回给客户端。
说明:服务端应用服务引用spyne包,调用系统shell命令引用commands包,wsdl客户端使用suds包, 包的安装惯例直接easy_install或pip即可,不多说,直接上代码。
服务端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from spyne import Application
from spyne import rpc
from spyne import ServiceBase
from spyne import Iterable, Unicode
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
import commands
# step1: Defining a Spyne Service
class HelloWorldService(ServiceBase):
@rpc(Unicode, _returns=Iterable(Unicode))
def say_hello(self, name):
(status, output) = commands.getstatusoutput(str(name))
yield status
yield output
# step2: Glue the service definition, input and output protocols
soap_app = Application([HelloWorldService], 'spyne.examples.hello.soap',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11())
# step3: Wrap the Spyne application with its wsgi wrapper
wsgi_app = WsgiApplication(soap_app)
if __name__ == '__main__':
import logging
from wsgiref.simple_server import make_server
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
logging.info("listening to http://127.0.0.1:6789")
logging.info("wsdl is at: http://localhost:6789/?wsdl")
server = make_server('127.0.0.1', 6789, wsgi_app)
server.serve_forever()
客户端:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from suds.client import Client
h_clt = Client('http://localhost:6789/?wsdl')
h_clt.options.cache.clear()
result = h_clt.service.say_hello('ps ')
print result
客户端调用结果: