Python grpc.Future() Examples

The following are 10 code examples of grpc.Future(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module grpc , or try the search function .
Example #1
Source File: _client.py    From opentelemetry-python with Apache License 2.0 7 votes vote down vote up
def _trace_result(self, guarded_span, rpc_info, result):
        # If the RPC is called asynchronously, release the guard and add a
        # callback so that the span can be finished once the future is done.
        if isinstance(result, grpc.Future):
            result.add_done_callback(
                _make_future_done_callback(guarded_span.release(), rpc_info)
            )
            return result
        response = result
        # Handle the case when the RPC is initiated via the with_call
        # method and the result is a tuple with the first element as the
        # response.
        # http://www.grpc.io/grpc/python/grpc.html#grpc.UnaryUnaryMultiCallable.with_call
        if isinstance(result, tuple):
            response = result[0]
        rpc_info.response = response
        return result 
Example #2
Source File: stub_manager.py    From loopchain with Apache License 2.0 6 votes vote down vote up
def call_async(self, method_name, message, call_back=None, timeout=None, is_stub_reuse=True) -> grpc.Future:
        if timeout is None:
            timeout = conf.GRPC_TIMEOUT
        if call_back is None:
            call_back = self.print_broadcast_fail
        self.__make_stub(is_stub_reuse)

        def done_callback(result: _Rendezvous):
            if result.code() == grpc.StatusCode.OK:
                self.__update_last_succeed_time()
            call_back(result)

        try:
            stub_method = getattr(self.__stub, method_name)
            feature_future = stub_method.future(message, timeout)
            feature_future.add_done_callback(done_callback)
            return feature_future
        except Exception as e:
            logging.warning(f"gRPC call_async fail method_name({method_name}), message({message}): {e}, "
                            f"target({self.__target})") 
Example #3
Source File: exception_interceptor.py    From google-ads-python with Apache License 2.0 6 votes vote down vote up
def _handle_grpc_failure(self, response):
        """Attempts to convert failed responses to a GoogleAdsException object.

        Handles failed gRPC responses of by attempting to convert them
        to a more readable GoogleAdsException. Certain types of exceptions are
        not converted; if the object's trailing metadata does not indicate that
        it is a GoogleAdsException, or if it falls under a certain category of
        status code, (INTERNAL or RESOURCE_EXHAUSTED). See documentation for
        more information about gRPC status codes:
        https://github.com/grpc/grpc/blob/master/doc/statuscodes.md

        Args:
            response: a grpc.Call/grpc.Future instance.

        Raises:
            GoogleAdsException: If the exception's trailing metadata
                indicates that it is a GoogleAdsException.
            RpcError: If the exception's is a gRPC exception but the trailing
                metadata is empty or is not indicative of a GoogleAdsException,
                or if the exception has a status code of INTERNAL or
                RESOURCE_EXHAUSTED.
            Exception: If not a GoogleAdsException or RpcException the error
                will be raised as-is.
        """
        raise self._get_error_from_response(response) 
Example #4
Source File: _client.py    From python-grpc with Apache License 2.0 6 votes vote down vote up
def _trace_result(self, guarded_span, rpc_info, result):
        # If the RPC is called asynchronously, release the guard and add a callback
        # so that the span can be finished once the future is done.
        if isinstance(result, grpc.Future):
            result.add_done_callback(
                _make_future_done_callback(guarded_span.release(
                ), rpc_info, self._log_payloads, self._span_decorator))
            return result
        response = result
        # Handle the case when the RPC is initiated via the with_call
        # method and the result is a tuple with the first element as the
        # response.
        # http://www.grpc.io/grpc/python/grpc.html#grpc.UnaryUnaryMultiCallable.with_call
        if isinstance(result, tuple):
            response = result[0]
        rpc_info.response = response
        if self._log_payloads:
            guarded_span.span.log_kv({'response': response})
        if self._span_decorator is not None:
            self._span_decorator(guarded_span.span, rpc_info)
        return result 
Example #5
Source File: test__eventloop.py    From python-ndb with Apache License 2.0 5 votes vote down vote up
def test_queue_rpc(self):
        loop = self._make_one()
        callback = mock.Mock(spec=())
        rpc = mock.Mock(spec=grpc.Future)
        loop.queue_rpc(rpc, callback)
        assert list(loop.rpcs.values()) == [callback]

        rpc_callback = rpc.add_done_callback.call_args[0][0]
        rpc_callback(rpc)
        rpc_id, rpc_result = loop.rpc_results.get()
        assert rpc_result is rpc
        assert loop.rpcs[rpc_id] is callback 
Example #6
Source File: test__eventloop.py    From python-ndb with Apache License 2.0 5 votes vote down vote up
def test_run0_rpc(self):
        rpc = mock.Mock(spec=grpc.Future)
        callback = mock.Mock(spec=())

        loop = self._make_one()
        loop.rpcs["foo"] = callback
        loop.rpc_results.put(("foo", rpc))

        loop.run0()
        assert len(loop.rpcs) == 0
        assert loop.rpc_results.empty()
        callback.assert_called_once_with(rpc) 
Example #7
Source File: _remote.py    From python-ndb with Apache License 2.0 5 votes vote down vote up
def exception(self):
        """Calls :meth:`grpc.Future.exception` on :attr:`future`."""
        # GRPC will actually raise FutureCancelledError.
        # We'll translate that to our own Cancelled exception and *return* it,
        # which is far more polite for a method that *returns exceptions*.
        try:
            return self.future.exception()
        except grpc.FutureCancelledError:
            return exceptions.Cancelled() 
Example #8
Source File: _remote.py    From python-ndb with Apache License 2.0 5 votes vote down vote up
def result(self):
        """Calls :meth:`grpc.Future.result` on :attr:`future`."""
        return self.future.result() 
Example #9
Source File: _remote.py    From python-ndb with Apache License 2.0 5 votes vote down vote up
def cancel(self):
        """Calls :meth:`grpc.Future.cancel` on attr:`cancel`."""
        return self.future.cancel() 
Example #10
Source File: client_interceptor.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def _trace_future_exception(self, response):
        # Trace the exception for a grpc.Future if any
        exception = response.exception()

        if exception is not None:
            exception = str(exception)

        self.tracer.add_attribute_to_current_span(
            attribute_key=attributes_helper.COMMON_ATTRIBUTES.get(
                ATTRIBUTE_ERROR_MESSAGE),
            attribute_value=exception)