11.8 实现远程方法调用

问题

You want to implement simple remote procedure call (RPC) on top of a message passinglayer, such as sockets, multiprocessing connections, or ZeroMQ.

解决方案

RPC is easy to implement by encoding function requests, arguments, and return valuesusing pickle, and passing the pickled byte strings between interpreters. Here is anexample of a simple RPC handler that could be incorporated into a server:

class RPCProxy:def init(self, connection):self._connection = connectiondef getattr(self, name):def do_rpc(*args, **kwargs):self._connection.send(json.dumps((name, args, kwargs)))result = json.loads(self._connection.recv())return result
return do_rpc

One complicated factor in implementing RPC is how to handle exceptions. At the veryleast, the server shouldn’t crash if an exception is raised by a method. However, themeans by which the exception gets reported back to the client requires some study. Ifyou’re using pickle, exception instances can often be serialized and reraised in theclient. If you’re using some other protocol, you might have to think of an alternativeapproach. At the very least, you would probably want to return the exception string inthe response. This is the approach taken in the JSON example.For another example of an RPC implementation, it can be useful to look at the imple‐mentation of the SimpleXMLRPCServer and ServerProxy classes used in XML-RPC, asdescribed in Recipe 11.6.

文章导航