python编写web service,pythonwebservice,以前都是用C#写webs


以前都是用C#写webservice,而现在多以php做开发,也很少用windows的平台。就打算用python来写一下

网上找了下相关的库,使用到的如下:

python2.7+soaplib2.0+pyyaml3.1+MySQLdb

以前配置都是用的ini文件,这次使用了yaml,使用还是很方便的

先来个例子

#-*- coding:utf-8 -*-import soaplibfrom soaplib.core.service import soapfrom soaplib.core.service import DefinitionBasefrom soaplib.core.model.primitive import String, Integerfrom soaplib.core.server import wsgifrom soaplib.core.model.clazz import Array'''This is a simple HelloWorld example to show the basics of writinga webservice using soaplib, starting a server, and creating a serviceclient.'''class HelloWorldService(DefinitionBase):    @soap(String, Integer, _returns=Array(String))    def say_hello(self, name, times):        '''        Docstrings for service methods appear as documentation in the wsdl        <b>what fun</b>        @param name the name to say hello to        @param the number of times to say hello        @return the completed array        '''        results = []        for i in range(0, times):            results.append('Hello, %s' % name)        return resultsif __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', 8080, wsgi_application)        server.serve_forever()    except ImportError:        print "Error: example server code requires Python >= 2.5"

C#客户端添加web引用,命名空间为PyWs

调用代码如下:

  PyWs.Application app = new PyWs.Application();  PyWs.say_hello sh = new PyWs.say_hello();  sh.name="word";  sh.times=5;  PyWs.say_helloResponse re = app.say_hello(sh);

此处的re就是返回的结果,当然如果有中文的情况,建议结果返回时使用base64编码

评论关闭