现在的位置: 首页 > web前端 > 正文

python webservice hello world

2019年08月04日 web前端 ⁄ 共 2640字 ⁄ 字号 评论关闭

最近在搞基于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
2 from soaplib.core.util.wsgi_wrapper import run_twisted #发布服务
3 from soaplib.core.server import wsgi
4 from soaplib.core.service import DefinitionBase  #所有服务类必须继承该类
5 from soaplib.core.service import soap  #声明注解
6 from soaplib.core.model.clazz import Array #声明要使用的类型
7 from soaplib.core.model.clazz import ClassModel  #若服务返回类,该返回类必须是该类的子类
8 from soaplib.core.model.primitive import Integer,String 
01 class C_ProbeCdrModel(ClassModel):
02     __namespace__ = "C_ProbeCdrModel"
03     Name=String
04     Id=Integer
05 class HelloWorldService(DefinitionBase):  #this
is a web service
06     @soap(String,_returns=String)    #声明一个服务,标识方法的参数以及返回值
07     def say_hello(self,name):
08         return 'hello
%s!'
%name
09     @soap(_returns=Array(String))
10     def GetCdrArray(self):
11         L_Result=["1","2","3"]
12         return L_Result
13     @soap(_returns=C_ProbeCdrModel)
14     def GetCdr(self):
    
#返回的是一个类,该类必须是ClassModel的子类,该类已经在上面定义
15         L_Model=C_ProbeCdrModel()
16         L_Model.Name=L_Model.Name
17         L_Model.Id=L_Model.Id
18         return L_Model
19 if __name__=='_main__':
20     soap_app=soaplib.core.Application([HelloWorldService], 'tns')
21     wsgi_app=wsgi.Application(soap_app)
22     print 'listening
on 127.0.0.1:7789'
23     print 'wsdl
is at: http://127.0.0.1:7789/SOAP/?wsdl'
24     run_twisted(
( (wsgi_app, 
"SOAP"),), 7789)
25 if __name__=='__main__':  #发布服务
26     try:
27         from wsgiref.simple_server import make_server
28         soap_application = soaplib.core.Application([HelloWorldService], 'tns')
29         wsgi_application = wsgi.Application(soap_application)
30         server = make_server('localhost'7789,
wsgi_application)
31         server.serve_forever()
32     except ImportError:
33         print 'error'

python server.py可以直接运行服务了。运行服务后打开浏览器,地址栏上键入: http://localhost:7789/SOAP/?wsdl就能看到描述服务的xml文档了。

请求服务:

需要用到suds库:

    具体可以在https://fedorahosted.org/suds/下载。安装跟上面一样。

python交互模式下键入:

1 from suds.client import Client
2  
3 test=Client('http://localhost:7789/SOAP/?wsdl')
4  
5 print test.service.say_hello('volador')

这样就调用了say_hello这个服务了。

抱歉!评论已关闭.