最近在搞基于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
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"
05
class
HelloWorldService(DefinitionBase):
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"
]
13
@soap
(_returns
=
C_ProbeCdrModel)
15
L_Model
=
C_ProbeCdrModel()
16
L_Model.Name
=
L_Model.Name
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__'
:
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()
python server.py可以直接运行服务了。运行服务后打开浏览器,地址栏上键入:
http://localhost:7789/SOAP/?wsdl
就能看到描述服务的xml文档了。
请求服务:
需要用到suds库:
具体可以在https://fedorahosted.org/suds/ 下载。安装跟上面一样。
python交互模式下键入:
1
from
suds.client
import
Client
3
test
=
Client(
'http://localhost:7789/SOAP/?wsdl'
)
5
print
test.service.say_hello(
'volador'
)
这样就调用了say_hello这个服务了。