• 用soaplib实现webservice
    • 问题
    • 解法

    用soaplib实现webservice

    问题

    如何用soaplib实现webservice?

    解法

    Optio的soaplib通过用装饰器指定类型,从而直接编写SOAP web service。而且它也是到目前为止,唯一为web service提供WSDL文档的Python类库。

    1. import web
    2. from soaplib.wsgi_soap import SimpleWSGISoapApp
    3. from soaplib.service import soapmethod
    4. from soaplib.serializers import primitive as soap_types
    5. urls = ("/hello", "HelloService",
    6. "/hello.wsdl", "HelloService",
    7. )
    8. render = web.template.Template("$def with (var)\n$:var")
    9. class SoapService(SimpleWSGISoapApp):
    10. """Class for webservice """
    11. #__tns__ = 'http://test.com'
    12. @soapmethod(soap_types.String,_returns=soap_types.String)
    13. def hello(self,message):
    14. """ Method for webservice"""
    15. return "Hello world "+message
    16. class HelloService(SoapService):
    17. """Class for web.py """
    18. def start_response(self,status, headers):
    19. web.ctx.status = status
    20. for header, value in headers:
    21. web.header(header, value)
    22. def GET(self):
    23. response = super(SimpleWSGISoapApp, self).__call__(web.ctx.environ, self.start_response)
    24. return render("\n".join(response))
    25. def POST(self):
    26. response = super(SimpleWSGISoapApp, self).__call__(web.ctx.environ, self.start_response)
    27. return render("\n".join(response))
    28. app=web.application(urls, globals())
    29. if __name__ == "__main__":
    30. app.run()

    可以用soaplib客户端测试一下:

    1. >>> from soaplib.client import make_service_client
    2. >>> from test import HelloService
    3. >>> client = make_service_client('http://localhost:8080/hello', HelloService())
    4. >>> client.hello('John')
    5. 'Hello world John'

    可以在http://localhost:8080/hello.wsdl查看WSDL。

    欲了解更多,请查看 soaplib,