python webservice服务_python webservice hello world | 学步园

最近在搞基于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_wrapperimport run_twisted#发布服务

3

from soaplib.core.serverimport wsgi

4

from soaplib.core.serviceimport DefinitionBase#所有服务类必须继承该类

5

from soaplib.core.serviceimport soap#声明注解

6

from soaplib.core.model.clazzimport Array#声明要使用的类型

7

from soaplib.core.model.clazzimport ClassModel#若服务返回类,该返回类必须是该类的子类

8

from soaplib.core.model.primitiveimport 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_serverimport 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库:

python交互模式下键入:

1

from suds.clientimport Client

2

3

test=Client('http://localhost:7789/SOAP/?wsdl')

4

5

print test.service.say_hello('volador')

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值