Python2.7下發布web service(二):服務發佈示例

參考資料:(1) soaplib官方教程 html

               (2) 官方示例,簡單的hello world service python

                (3) 一份較好的中文文檔示例 git

服務聲明

import soaplib
from soaplib.core.service import rpc, DefinitionBase,soap #官方文檔缺乏import soap
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

#輸出結果:
#(stringArray){
#   string[] = 
#      "Hello, Dave",
#      "Hello, Dave",
#      "Hello, Dave",
#      "Hello, Dave",
#      "Hello, Dave",
# }
客戶端調用服務,須要安裝suds。 下載,cmd進目錄,setup.py install
相關文章
相關標籤/搜索