歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python實現簡單xml-rpc服務器

Python實現簡單xml-rpc服務器

日期:2017/3/1 9:55:36   编辑:Linux編程

以下程序均來自《Python.UNIX和Linux系統管理指南》http://www.linuxidc.com/Linux/2013-06/86448.htm

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'">

Copyright © Linux教程網 All Rights Reserved