服务器(CherryPy 3.2.0):
import cherrypy
class XMLRPCServer(cherrypy._cptools.XMLRPCController):
def index(self):
return 'index'
index.exposed = True
if __name__ =='__main__':
cherrypy.config.update({
'server.thread_pool': 1,
'request.dispatch': cherrypy.dispatch.XMLRPCDispatcher,
'tools.xmlrpc.on': True,
'tools.xmlrpc.allow_none': 0,
})
cherrypy.quickstart(XMLRPCServer())
客户端(Python 2.7.1):
import xmlrpclib
svc = xmlrpclib.ServerProxy('http://127.0.0.1:8080')
r = svc.index()
错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/xmlrpclib.py", line 1224, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python2.7/xmlrpclib.py", line 1575, in __request
verbose=self.__verbose
File "/usr/lib/python2.7/xmlrpclib.py", line 1264, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python2.7/xmlrpclib.py", line 1312, in single_request
response.msg,
xmlrpclib.ProtocolError: <ProtocolError for 127.0.0.1:8080/RPC2: 404 Not Found>
如何在CherryPy中启用xml-rpc,我用Google搜索并阅读文档但仍然卡住了。
答案 0 :(得分:2)
来自XMLRPCController
文档的相关引用:
XMLRPCDispatcher剥离任何/ RPC2前缀;如果你没有在你的URL中使用/ RPC2, 您可以安全地跳过打开XMLRPCDispatcher。
以下工作正常。还要注意分离全局和应用程序配置,因为你已将它们混合起来。
sever.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cherrypy
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 8
},
'/' : {
'tools.xmlrpc.allow_none' : True
}
}
class Api(cherrypy._cptools.XMLRPCController):
@cherrypy.expose
def mul(self, a, b):
return a * b
if __name__ == '__main__':
cherrypy.quickstart(Api(), '/api', config)
client.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import xmlrpclib
rpc = xmlrpclib.ServerProxy('http://localhost:8080/api')
print rpc.mul(2, 6)