最近在搞基于python的webservice项目,今天为把环境给配好,折腾了不少时间,还是把配的过程记录下来,以后备用:
首先你系统上要有python,这个不必说啦,我系统上用的是2.7+
其次,要用python进行webservice开发,还需要一些库:
lxml :
命令行下 sudo easy_install lxml 就能安装
pytz :
命令行下 sudo easy_install pytz 就能安装
soaplib:
进行webservice开发必须要用的库,可以在https://github.com/volador/soaplib拿到,注意要先安装上面两个插件再安装这个,因为这个依赖于上面两个插件,把zip拿下来后解压,sudo python setup.py install 就能安装了。
Soaplib is an easy to use python library for publishing soap web services using WSDL 1.1 standard, and answering SOAP 1.1 requests. With a very small amount of code, soaplib allows you to write a useful web service and deploy it as a WSGI application.完成上面步骤后就能进行webservice发布了,看下helloworld:
直接贴代码:server.py
import soaplib from soaplib.core.util.wsgi_wrapper import run_twisted #发布服务 from soaplib.core.server import wsgi from soaplib.core.service import DefinitionBase #所有服务类必须继承该类 from soaplib.core.service import soap #声明注解 from soaplib.core.model.clazz import Array #声明要使用的类型 from soaplib.core.model.clazz import ClassModel #若服务返回类,该返回类必须是该类的子类 from soaplib.core.model.primitive import Integer,String
class C_ProbeCdrModel(ClassModel): __namespace__ = "C_ProbeCdrModel" Name=String Id=Integer class HelloWorldService(DefinitionBase): #this is a web service @soap(String,_returns=String) #声明一个服务,标识方法的参数以及返回值 def say_hello(self,name): return 'hello %s!'%name @soap(_returns=Array(String)) def GetCdrArray(self): L_Result=["1","2","3"] return L_Result @soap(_returns=C_ProbeCdrModel) def GetCdr(self): #返回的是一个类,该类必须是ClassModel的子类,该类已经在上面定义 L_Model=C_ProbeCdrModel() L_Model.Name=L_Model.Name L_Model.Id=L_Model.Id return L_Model if __name__=='_main__': soap_app=soaplib.core.Application([HelloWorldService], 'tns') wsgi_app=wsgi.Application(soap_app) print 'listening on 127.0.0.1:7789' print 'wsdl is at: http://127.0.0.1:7789/SOAP/?wsdl' run_twisted( ( (wsgi_app, "SOAP"),), 7789) 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'
请求服务:
需要用到suds库:
具体可以在https://fedorahosted.org/suds/下载。安装跟上面一样。
python交互模式下键入:
from suds.client import Client test=Client('http://localhost:7789/SOAP/?wsdl') print test.service.say_hello('volador')
这样就调用了say_hello这个服务了。