Python实现简单xml-rpc服务器
XML-RPC在两个进程之间交换指定格式的XML文档,以实现远程过程调用,还有一个更加高级的工具Pyro,由于现在的版本是Pyro4与书中所使用的版本有很大差异,等有时间再去研究一下
xml_rpc_server.py
#!/usr/bin/en python
import SimpleXMLRPCServer
import os
def ls(directory):
try:
return os.listdir(directory)
except OSError:
return []
def ls_boom(directory):
return os.listdir(directory)
def cb(obj):
print "OPBJECT::", obj
print "OBJECT.__class__::", obj.__class__
return obj.cb()
if __name__ == '__main__':
s = SimpleXMLRPCServer.SimpleXMLRPCServer(('127.0.0.1', 8765))
s.register_function(ls)
s.register_function(ls_boom)
s.register_function(cb)
s.serve_forever()
运行结果:
服务端
[root@CentOS python]# python xml_rpc_server.py
127.0.0.1 - - [19/Jun/2013 12:04:05] "POST /RPC2 HTTP/1.1" 200 -
127.0.0.1 - - [19/Jun/2013 12:04:19] "POST /RPC2 HTTP/1.1" 200 -
127.0.0.1 - - [19/Jun/2013 12:04:36] "POST /RPC2 HTTP/1.1" 200 -
127.0.0.1 - - [19/Jun/2013 12:04:50] "POST /RPC2 HTTP/1.1" 200 -
客户端
[root@centos python]# python
Python 2.7.5 (default, Jun 19 2013, 07:19:44)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xmlrpclib
>>> x = xmlrpclib.ServerProxy('http://localhost:8765')
>>> x.ls('.')
['check_web.py', 'ftp_client.py', 'helloworld.pdf', 'email_attachment.py', 'sendemail.py', 'pdf.py', 'xml_rpc_server.py', 'diskreport.py', 'httplib_check_web.py', 'check_tcp_port.py', 'disk_report.pdf']
>>> x.ls_boom('.')
['check_web.py', 'ftp_client.py', 'helloworld.pdf', 'email_attachment.py', 'sendemail.py', 'pdf.py', 'xml_rpc_server.py', 'diskreport.py', 'httplib_check_web.py', 'check_tcp_port.py', 'disk_report.pdf']
>>> x.ls('/foo')
[]
>>> x.ls_boom('/foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python27/lib/python2.7/xmlrpclib.py", line 1224, in __call__
return self.__send(self.__name, args)
File "/usr/local/python27/lib/python2.7/xmlrpclib.py", line 1578, in __request
verbose=self.__verbose
File "/usr/local/python27/lib/python2.7/xmlrpclib.py", line 1264, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/local/python27/lib/python2.7/xmlrpclib.py", line 1297, in single_request
return self.parse_response(response)
File "/usr/local/python27/lib/python2.7/xmlrpclib.py", line 1473, in parse_response
return u.close()
File "/usr/local/python27/lib/python2.7/xmlrpclib.py", line 793, in close
raise Fault(**self._stack[0])
xmlrpclib.Fault: <Fault 1: "<type 'exceptions.OSError'>:[Errno 2] No such file or directory: '/foo'">