针对Python的WebService开发,开发者讨论最多的库是soaplib(官方地址:http://soaplib.github.io/soaplib/2_0/index.html),但从其官网可知,其最新版本“soaplib-2.0.0-beta2”从2011年3月发布后就不再进行更新了。通过阅读soaplib的官方文档,可知其不再维护后已经转向了一个新的项目:rpclib(官方地址:http://github.com/arskom/rpclib)进行后续开发,但在rpclib的readme中,介绍了rpclib已经更名为spyne,并将持续进行更新,so,那就选用spyne进行开发了。
客户端调用WebService一般应用suds库。
当接口中参数类型都为简单类型时(Integer, Decimal, Float, String, ..),除增加rpc装饰器外,接口代码与一般的Python方法代码是一样的:
from spyne import Application, rpc, ServiceBase
from spyne import Integer, Unicode, Array, ComplexModel
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from wsgiref.simple_server import make_server
class SomeSampleServices(ServiceBase):
@rpc(Unicode, Unicode _returns=Unicode)
def make_project(self, name, version):
pass
if __name__ == "__main__":
soap_app = Application([SomeSampleServices],
'SampleServices',
in_protocol=Soap11(validator="lxml"),
out_protocol=Soap11())
wsgi_app = WsgiApplication(soap_app)
server = make_server(ip, port, wsgi_app)
sys.exit(server.serve_forever())
客户端调用代码:
from suds.client import Client
client = Client("http://%s:%s/?wsdl" % (ip, port))
ret = client.service.make_project("Test", "1.0.0")
当接口中数据类型为Complex数据类型(类型中包含类型)时,需要以类的方式定义类型,且继承于:spyne.model.complex.ComplexModel
class Project(ComplexModel):
name = Unicode
version = Unicode
客户端调用时,suds库提供了两种方式,第一种方式是应用factory子命名空间的方式,即先创建一个Complex数据对象,再对其属性进行赋值:
from suds.client import Client
client = Client("http://%s:%s/?wsdl" % (ip, port))
project = client.factory.create("Project")
project.name = "Test"
project.version = "1.0.0"
client.service.make_project(project)
另一种方式是直接应用Python字典的方式传入参数:
from suds.client import Client
client = Client("http://%s:%s/?wsdl" % (ip, port))
project = {}
project["name"] = "Test"
project["version"] = "1.0.0"
client.service.make_project(project)
可以发现,第二种方式编写更为方便,且更易理解
当参数为Array(数组)型的变量时,接口代码如下:
class Project(ComplexModel):
name = Unicode
version = Unicode
class SomeSampleServices(ServiceBase):
@rpc(Array(Project), _returns=Unicode)
def make_prodect(self, project):
pass
调用时,需要创建对应类型的Array对象,对象创建好后,就可以应用Python的list对象对其进行赋值了:
from suds.client import Client
client = Client("http://%s:%s/?wsdl" % (ip, port))
projects = client.factory.create("ProjectArray")
projects.project = [project1, project2]
client.service.make_project(projects)
附:
spyne_docs = "http://spyne.io/docs/2.10/"
suds_docs = "https://fedorahosted.org/suds/wiki/Documentation"