python通过webservice连接cmdbuild
cmdbuild的部署可以查看文章:http://20988902.blog.iyunv.com/805922/1541289部署成功后,访问http://192.168.1.1:8080/cmdbuild/services/soap/ 就能看到所有的webservice方法,证明server这边已经ready了
cmdbuild webservice官方说明文档:http://download.iyunv.com/detail/siding159/7888309
下面是使用python开发webservice client的方法:
1.模块
python的webservice模块有很多,这里使用suds来进行连接
可以通过 easy_install suds来安装suds,十分方便
suds官方文档:https://fedorahosted.org/suds/wiki/Documentation
2.日志
suds是通过logging来实现日志的,所以配置logging后,就可以看到soap连接过程中的所有数据
import logging
logging.basicConfig(level=logging.DEBUG, filename='myapp.log')
logging.getLogger('suds.client').setLevel(logging.DEBUG)
# logging.getLogger('suds.transport').setLevel(logging.DEBUG)
# logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG)
# logging.getLogger('suds.wsdl').setLevel(logging.DEBUG)
suds提供了四种日志类型,可以根据需要来配置
3.连接
from suds.client import Client
url = 'http://192.168.8.190:8080/cmdbuild/services/soap/Private?wsdl'
client = Client(url)
print client
r=client.service.getCard('Cabinet',2336)
实例化Client后,可以print client来输出次webservice提供的接口,也就是wsdl文件的说明
通过r=client.service.getCard('Cabinet',2336)来调用webservice的getCard接口,并输入参数,print client的输出结果会有每个接口需要输入的参数说明
但是这样连接后,会报错:suds.WebFault: Server raised fault: 'An error was discovered processing theheader'
因为cmdbuild需要wsse安全验证
4.wsse安全验证
为client实例设置wsse参数
from suds.wsse import *
from suds.client import Client
url = 'http://192.168.8.190:8080/cmdbuild/services/soap/Private?wsdl'
client = Client(url)
security = Security()
token = UsernameToken('admin', 'admin')
security.tokens.append(token)
client.set_options(wsse=security)
r=client.service.getCard('Cabinet',2336)
UsernameToken的参数是访问的账号和密码
继续运行程序后,可能会报错:suds.WebFault: Server raised fault: 'The security token could not be authenticated or authorized'‘
解决方法是,把cmdb的auth配置文件的force.ws.password.digest参数设置为false,并重启tomcat,auth.conf路径 tomcat/webapps/WEB-INI/conf/auth.conf
5.处理返回来的xml
继续运行,会报错:xml.sax._exceptions.SAXParseException: :2:0: syntax error
原因是程序在解析返回的xml文件的时候出错了,通过日志,我们可以看到返回来的body是这样的
--uuid:b16cf808-f566-4bad-a92c-a7d303d33211
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml";
Content-Transfer-Encoding: binary
Content-ID:
Useradmin6084CabinetStatus终止RentalAmount9000.00Description机房 Room 1 D14BeginDate12/08/14 18:03:17ContractCodeD14168Trusteeship科技有限公司NotesStatusN2325Room机房Room 1StartDate23/09/10Id2336Capacity0NoUsed0IdClass42216CibinetNUm152014-08-12T18:03:17.839+08:00Cabinet2336runtime.privilegeswriteadmin
--uuid:b16cf808-f566-4bad-a92c-a7d303d33211--
发现在xml字符串之外还有很多没用的信息,所以我们需要在接受了返回之后,对返回结果进行处理(把它转化成标准的xml字符串)后,再进行xml的解析
import re
from suds.wsse import *
from suds.client import Client
from suds.plugin import MessagePlugin
url = 'http://192.168.8.190:8080/cmdbuild/services/soap/Private?wsdl'
class MyPlugin(MessagePlugin):
def received(self, context):
reply_new=re.findall("
页:
[1]