此模块包含对构建符合标准请求和响应模式的远程服务有用的类。为了符合该模式,服务必须提供以下类:
# Each service instance only handles a single request and is then discarded. # Make these objects light weight. class Service(object): # It must be possible to construct service objects without any parameters. # If your constructor needs extra information you should provide a # no-argument factory function to create service instances. def __init__(self): ... # Each remote method must use the 'remote' decorator, passing the request # and response message types. The remote method itself must take a single # parameter which is an instance of RequestMessage and return an instance # of ResponseMessage. @method(RequestMessage, ResponseMessage) def remote_method(self, request): # Return an instance of ResponseMessage. # A service object may optionally implement a 'initialize_request_state' # method that takes as a parameter a single instance of a RequestState. If # a service does not implement this method it will not receive the request # state. def initialize_request_state(self, state): ...
服务类是一个可以提供上述功能的便捷基类。它实现了服务的所有必需的和可选的方法。它还提供了创建工厂函数的简便方法,可将永久性全局状态传递给新的服务实例。
远程装饰器用于声明哪些类方法属于服务 RPC。但请注意,这个修饰器不负责处理套接字和各种底层 RPC 协议。虽然该修饰器会确保您能够使用正确的请求类型,但它不会检查是否进行了初始化。
在将远程修饰器用于某个方法时,被封装的方法会具有与该修饰器相关的“远程”属性。此属性包含方法实现所需的 request_type
和 response_type
。
远程修饰器本身并没有为子类远程方法提供任何支持。为了扩展服务,请使用子类方法进行重新修饰。例如:
class MyService(Service): @method(DoSomethingRequest, DoSomethingResponse) def do_something(self, request): ... implement do-something ... class MyBetterService(MyService): @method(DoSomethingRequest, DoSomethingResponse) def do_something(self, request): response = super(MyBetterService, self).do_something.remote.method(request) ... do something with response ... return response