python读取webservice

网上最多的是suds模块,这里也使用suds。

1、安装:

  和所有python模块安装一样,可以使用easy_install或pip在线安装,也可以下载离线安装.

  https://pypi.python.org/pypi/suds/

2、简单入门:

  

import logging
from suds.client import Client   
from suds.xsd.doctor import ImportDoctor,Import
#日志,suds下的各个python模块或者说python文件大多都使用了logging模块进行日志记录,我们只需要设置好日志的等级、格式、路径等,就可以进行对应模块的日志记录了

 logging.basicConfig(level=logging.INFO,

format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',

datefmt='%a, %d %b %Y %H:%M:%S',

filename='/tmp/test.log',

filemode='w')

logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG)
#Import和DoctorImport是提供wsdl中缺少的import标签的
imp = Import("http://www.w3.org/2001/XMLSchema",location="http://www.w3.org/2001/XMLSchema.xsd")
imp.filter.add("http://WebXml.com.cn/")
doctor=ImportDoctor(imp)
url ='http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx?wsdl'
client = Client(url,doctor=doctor)
r = client.service.getStationName()

3、WSDL

  wsdl使用xml文件格式,xsd规范对外提供webservice接口。suds模块很大一部分是对于wsdl对应的xml文件的解析。所以需要对wsdl有个系统的了解。

  http://www.phpstudy.net/e/wsdl/

4、suds使用中的问题

  suds将xml中的element、complexType等等都定义成了类,新建Client对象时会解析wsdl的xml文档。将文档中的types,types下的element,import,service等全部转换成python中的对象。然后是使用service使用对应服务方法。

  suds使用时出现错误:Type not found: '(schema, http://www.w3.org/2001/XMLSchema, )'

  只是因为需要访问的wsdl中使用到了 http://www.w3.org/2001/XMLSchema中定义的对象,但是wsdl中没有使用import标签将 http://www.w3.org/2001/XMLSchema命名空间引入,引起错误。

  解决办法即添加如上添加doctor初始化选项。这里可能是使用其他的命名空间,使用同一的方法添加,可以使用doctor.add(imp)添加多个Import对象(多个命名空间)。

  imp.filter.add("")添加的是当前wsdl的targetNamespace,在wsdl的根标签中可以看到。