La biblioteca de servicios remotos
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Este módulo contiene clases que son útiles para compilar servicios remotos que coinciden con una solicitud estándar y un modelo de respuesta. Para coincidir con este modelo, un servicio debe ser como la clase siguiente:
# 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):
...
La clase Service es una base conveniente que proporciona la funcionalidad anterior. Implementa todos los métodos obligatorios y opcionales para un servicio. También tiene métodos de conveniencia para crear funciones de fábrica que pueden pasar el estado global persistente a una instancia de servicio nueva.
El decorador remoto se usa para declarar qué métodos de una clase están destinados a entregar RPC. Si bien este decorador no es responsable de entregar sockets y varios protocolos de RPC subyacentes. El decorador se asegura de que uses el tipo de solicitud correcto, pero no verifica la inicialización.
Cuando el decorador remoto se usa en un método, el método wrapper tendrá una propiedad "remota" asociada a él. Esta propiedad contiene los request_type
y response_type
esperados por la implementación del método.
Por sí mismo, el decorador remoto no proporciona ninguna asistencia para los métodos remotos de subclase. Con el fin de extender un servicio, usa los métodos de subclase para redecorar. Por ejemplo:
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
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-09-04 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eThis module facilitates building remote services that adhere to a standard request and response model, requiring each service to be structured like the provided \u003ccode\u003eService\u003c/code\u003e class example.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eService\u003c/code\u003e class serves as a base, providing essential and optional methods, and includes convenience methods for creating factory functions to manage persistent global state.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eremote\u003c/code\u003e decorator is used to designate RPC-serving methods within a class, ensuring the correct request and response types are used, though it doesn't handle initialization or underlying protocols.\u003c/p\u003e\n"],["\u003cp\u003eMethods wrapped with the \u003ccode\u003eremote\u003c/code\u003e decorator gain a \u003ccode\u003eremote\u003c/code\u003e property, which holds the \u003ccode\u003erequest_type\u003c/code\u003e and \u003ccode\u003eresponse_type\u003c/code\u003e information expected by the method's implementation.\u003c/p\u003e\n"],["\u003cp\u003eExtending service methods involves subclassing and redecorating with the \u003ccode\u003emethod\u003c/code\u003e decorator to ensure proper type handling and to call the super class.\u003c/p\u003e\n"]]],[],null,["# The Remote Service Library\n\nThis module contains classes that are useful for building remote services that conform to a standard request and response model. To conform to this model,\na service must be like the following class: \n\n```python\n# Each service instance only handles a single request and is then discarded.\n# Make these objects light weight.\nclass Service(object):\n\n # It must be possible to construct service objects without any parameters.\n # If your constructor needs extra information you should provide a\n # no-argument factory function to create service instances.\n def __init__(self):\n ...\n\n # Each remote method must use the 'remote' decorator, passing the request\n # and response message types. The remote method itself must take a single\n # parameter which is an instance of RequestMessage and return an instance\n # of ResponseMessage.\n @method(RequestMessage, ResponseMessage)\n def remote_method(self, request):\n # Return an instance of ResponseMessage.\n\n # A service object may optionally implement a 'initialize_request_state'\n # method that takes as a parameter a single instance of a RequestState. If\n # a service does not implement this method it will not receive the request\n # state.\n def initialize_request_state(self, state):\n ...\n```\n\nThe [Service](/appengine/docs/legacy/standard/python/tools/protorpc/remote/serviceclass) class is a convenient base class that provides the above functionality. It implements all required and optional methods for a service. It also has convenience methods for creating factory functions that can pass persistent global state to a new service instance.\n\nThe remote decorator is used to declare which methods of a class are meant to service RPCs. While this decorator is not responsible for handing sockets and various underlying RPC protocols. The decorator ensures that you are using the correct request type, but it does not check for initialization.\n\nWhen the remote decorator is used on a method, the wrapper method will have a\n'remote' property associated with it. This property contains the\n`request_type` and `response_type` expected by the method's implementation.\n\nOn its own, the remote decorator does not provide any support for subclassing\nremote methods. In order to extend a service, use the subclass methods to redecorate. For example: \n\n```python\nclass MyService(Service):\n\n @method(DoSomethingRequest, DoSomethingResponse)\n def do_something(self, request):\n ... implement do-something ...\n\nclass MyBetterService(MyService):\n\n @method(DoSomethingRequest, DoSomethingResponse)\n def do_something(self, request):\n response = super(MyBetterService, self).do_something.remote.method(request)\n ... do something with response ...\n return response\n```"]]