python里做webservice的库大体上有soappy,soaplib,xmlrpc等,详细参考http://wiki.python.org/moin/WebServices。这里具体说说soap方式
soappy应该是在google以后第一个出现,但是这个包好像已经老长时间不跟新,所以推荐soaplib,跟新比较频繁。http://soaplib.github.com/soaplib/2_0/是它的官网地址。
当然还有ZSI,这个用起来比较麻烦。
贴一个helloword的例子吧。
import soaplib
from soaplib.core.service import rpc, DefinitionBase
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz import Array
class HelloWorldService(DefinitionBase):
@soap(String,Integer,_returns=Array(String))
def say_hello(self,name,times):
results = []
for i in range(0,times):
results.append('Hello, %s'%name)
return results
if __name__=='__main__':
try:
from wsgiref.simple_server import make_server
soap_application = soaplib.core.Application([HelloWorldService], 'tns')
wsgi_application = wsgi.Application(soap_application)
server = make_server('localhost', 7789, wsgi_application)
server.serve_forever()
except ImportError:
print "Error: example server code requires Python >= 2.5"
这是个服务端,代码看起来比较容易懂。
>>> from suds.client import Client
>>> hello_client = Client('http://localhost:7789/?wsdl')
>>> result = hello_client.service.say_hello("Dave", 5)
>>> print result