Python:利用XML-RPC实现简单的远端过程调用
问题
我们希望能有一种简单的方法可以在远端机器上运行的Python程序中执行函数或者方法。
解决方案
也许实现一个远端过程调用机制最简单的方式是使用XML-RPC了。下面这个例子给出了一个简单的服务器,其中实现了键—值对的的存储:
from xmlrpc.server import SimpleXMLRPCServer
class KeyValueServer:
_rpc_methods_ = ['get', 'set', 'delete', 'exists', 'keys']
def __init__(self, address):
self._data = {
}
self._serv = SimpleXMLRPCServer(address, allow_none=True)
for name in self._rpc_methods_:
self._serv.register_function(getattr(self, name))
def get(self, name):
return self._data[name]
def set(self, name, value):
self._data[name] = value
def delete(self, name):
del self._data[name]
def exists(self, name):
return name in self._data
def keys(self):
return list(self._data)
def serve_forever(self):
return self._serv.serve_forever()
if __name__ == '__main__':
kvserv = KeyValueServer(('', 15000))
kvserv.serve_forever()
启动服务器端
D:\Python39\python.exe D:/My_Project/Socket网络编程/remote_server.py
127.0.0.1 - - [17/May/2023 08:40:09] "POST /RPC2 HTTP/1.1" 200 -
127.0.0.1 - - [17/May/2023 08:40:11] "POST /RPC2 HTTP/1.1" 200 -
127.0.0.1 - - [17/May/2023 08:40:13] "POST /RPC2 HTTP/1.1" 200 -
127.0.0.1 - - [17/May/2023 08:40:15] "POST /RPC2 HTTP/1.1" 200 -
127.0.0.1 - - [17/May/2023 08:40:17] "POST /RPC2 HTTP/1.1" 200 -
127.0.0.1 - - [17/May/2023 08:40:19] "POST /RPC2 HTTP/1.1" 200 -
下面代码展示了如何从客户端远程访问服务器:
from xmlrpc.client import ServerProxy
s = ServerProxy('http://localhost:15000', allow_none=True)
s.set('foo', 'bar')
s.set('spam', [1, 2, 3])
print(s.keys())
print(s.get('spam'))
s.delete('spam')
print(s.keys())
运行结果如下:
D:\Python39\python.exe D:/My_Project/Socket网络编程/client_client.py
['foo', 'spam']
[1, 2, 3]
['foo']
Process finished with exit code 0