Posts tagged ‘python’

Web services in Python with soaplib (1)

Surprisingly, there aren’t too many web services libraries in Python. On the one hand, we have ZSI, allegedly the most powerful one. However its documentation is outdated and the beginnings aren’t easy. Keeping my search I discovered soaplib. Soaplib is an easy to use python library for writing and calling soap web services. To install it follow these steps:

svn co https://svn.optio.webfactional.com/soaplib/trunk soaplib 
cd soaplib python setup.py install

Creating web services with soaplib is quite easy. This is the server:

from soaplib.wsgi_soap import SimpleWSGISoapApp
from soaplib.service import soapmethod
from soaplib.serializers.primitive import String, Integer, Array
 
class HelloWorldService(SimpleWSGISoapApp):
 
    @soapmethod(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__':
    from cherrypy._cpwsgiserver import CherryPyWSGIServer
    # this example uses CherryPy2.2, use cherrypy.wsgiserver.CherryPyWSGIServer for CherryPy 3.0
    server = CherryPyWSGIServer(('localhost',7789),HelloWorldService())
    server.start()

And this is the client:

from soaplib.client import make_service_client
from helloworld import HelloWorldService
client = make_service_client('http://localhost:7789/',HelloWorldService())
print client.say_hello("Dave",5)

As you can see writing a simple web service just takes a few seconds. This example passes primitive data types (String, integer …) to the remote method. We’ll see how to pass complex data another time.