這個模組包含的類別適合用於建構符合標準要求與回應模型的遠端服務。為遵循這個模型,服務的類別應如下所示:
# 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): ...
Service 類別是能夠提供上述功能的簡便基本類別。它可實作一項服務的所有必要及選用方法,另外也提供建立 Factory 函式的簡便方法,能夠將持續性的全域狀態傳遞給新服務執行個體。
系統會使用 remote 修飾器來宣告提供遠端程序呼叫 (RPC) 的是哪些類別方法,但這個修飾器不負責處理通訊端及各個基礎的遠端程序呼叫 (RPC) 通訊協定。該修飾器可確保您使用的是正確的要求類型,但不會檢查初始化過程。
針對方法使用 remote 修飾器時,包裝函式方法將出現相關聯的「remote」屬性。這個屬性包含實作方法預期的 request_type
和 response_type
。
remote 修飾器本身不支援將 remote 方法轉化為子類別,因此如果要擴充服務,請使用子類別方法來重新進行修飾。舉例來說:
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