當前位置: 首頁>>代碼示例>>Python>>正文


Python grpc.RpcError方法代碼示例

本文整理匯總了Python中grpc.RpcError方法的典型用法代碼示例。如果您正苦於以下問題:Python grpc.RpcError方法的具體用法?Python grpc.RpcError怎麽用?Python grpc.RpcError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在grpc的用法示例。


在下文中一共展示了grpc.RpcError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: seed

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def seed(stub, wallet_password="", seed_words="", seed_password=""):
    request = ln.InitWalletRequest(
        wallet_password=wallet_password.encode(),
        cipher_seed_mnemonic=[x.encode() for x in seed_words],
        recovery_window=5000,
        aezeed_passphrase=seed_password.encode()
    )

    try:
        response = stub.InitWallet(request)
    except grpc.RpcError as rpc_error_call:
        code = rpc_error_call.code()
        print(code, file=sys.stderr)
        details = rpc_error_call.details()
        print("err='RPCError InitWallet'")
        print("errMore=\"" + details + "\"")
        sys.exit(1)
    except:
        e = sys.exc_info()[0]
        print(e, file=sys.stderr)
        print("err='InitWallet'")
        sys.exit(1) 
開發者ID:rootzoll,項目名稱:raspiblitz,代碼行數:24,代碼來源:lnd.initwallet.py

示例2: command

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def command(self, dest, cmd, data, timeout):
        logging.info("sending %s to %d", cmd, dest)
        try:
            grpc_message = agent_pb2.RouteMessage(destination=dest, name=cmd)
            grpc_message.args.Pack(data)

        except Exception as e:
            return self._handle_route_result(cmd,
                                agent_pb2.RouteMessageResult(
                                    source=dest,
                                    error=agent_pb2.GenericError(
                                        kind=agent_pb2.GenericError.PayloadError,
                                        description="Unable to create message "
                                        "with payload: {}".format(e))))

        try:
            res = self._stub.route_command(grpc_message, timeout=timeout)
        except grpc.RpcError as e:
            res = self._handle_grpc_error(e, dest)
        return self._handle_route_result(cmd, res) 
開發者ID:cea-hpc,項目名稱:pcocc,代碼行數:22,代碼來源:Tbon.py

示例3: test_wrap_value_error

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def test_wrap_value_error(self):
        from google.gax.errors import InvalidArgumentError

        invalid_attribute_exc = grpc.RpcError()
        invalid_attribute_exc.code = lambda: grpc.StatusCode.INVALID_ARGUMENT

        def value_error_func(*dummy_args, **dummy_kwargs):
            raise invalid_attribute_exc

        value_error_callable = api_callable.create_api_call(
            value_error_func, _CallSettings())

        with self.assertRaises(ValueError) as exc_info:
            value_error_callable(None)

        self.assertIsInstance(exc_info.exception, InvalidArgumentError)
        self.assertEqual(exc_info.exception.args, (u'RPC failed',))
        self.assertIs(exc_info.exception.cause, invalid_attribute_exc) 
開發者ID:googleapis,項目名稱:gax-python,代碼行數:20,代碼來源:test_api_callable.py

示例4: next

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def next(self):
        while self.idx < len(self.errors):
            p4_error = p4runtime_pb2.Error()
            one_error_any = self.errors[self.idx]
            if not one_error_any.Unpack(p4_error):
                raise P4RuntimeErrorFormatException(
                    "Cannot convert Any message to p4.Error")
            if p4_error.canonical_code == code_pb2.OK:
                continue
            v = self.idx, p4_error
            self.idx += 1
            return v
        raise StopIteration


# P4Runtime uses a 3-level message in case of an error during the processing of
# a write batch. This means that if we do not wrap the grpc.RpcError inside a
# custom exception, we can end-up with a non-helpful exception message in case
# of failure as only the first level will be printed. In this custom exception
# class, we extract the nested error message (one for each operation included in
# the batch) in order to print error code + user-facing message.  See P4 Runtime
# documentation for more details on error-reporting. 
開發者ID:opennetworkinglab,項目名稱:fabric-p4test,代碼行數:24,代碼來源:base_test.py

示例5: run

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def run(self):
        self.status = 'running'
        try:
            self.receiver()
        except RpcError as rpc_error:
            logger.error('{code} {details}'.format(code=rpc_error.code(),
                                                   details=rpc_error.details()))
            self.error = rpc_error
        except Exception as e:
            logger.error('Unhandled exception happened')
            logger.error(str(e))
            self.error = e
            self.status = 'erroneous'
            raise
        finally:
            self.work_queue = Queue()
            self.rpc_handler = None
        self.status = 'finished' 
開發者ID:nokia,項目名稱:SROS-grpc-services,代碼行數:20,代碼來源:grpc_lib.py

示例6: _is_retryable_grpc_error

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def _is_retryable_grpc_error(error):
  """Predicate defining what is a retryable gRPC error."""
  non_retryable_errors = {
      grpc.StatusCode.INVALID_ARGUMENT,
      grpc.StatusCode.NOT_FOUND,
      grpc.StatusCode.ALREADY_EXISTS,
      grpc.StatusCode.PERMISSION_DENIED,
      grpc.StatusCode.FAILED_PRECONDITION,
      grpc.StatusCode.ABORTED,
      grpc.StatusCode.OUT_OF_RANGE,
      grpc.StatusCode.UNIMPLEMENTED,
      grpc.StatusCode.DATA_LOSS,
      grpc.StatusCode.UNAUTHENTICATED,
  }
  return (isinstance(error, grpc.RpcError) and
          error.code() not in non_retryable_errors) 
開發者ID:tensorflow,項目名稱:federated,代碼行數:18,代碼來源:remote_executor.py

示例7: test_wrong_certificates

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def test_wrong_certificates():
    url = endpoint_info.info

    trusted_cert, wrong_key, wrong_ca = prepare_certs(
        CERT_SERVER,
        CERT_BAD_CLIENT_KEY,
        CERT_BAD_CLIENT)
    creds = grpc.ssl_channel_credentials(root_certificates=trusted_cert,
                                         private_key=wrong_key, certificate_chain=wrong_ca)
    stub, request = prepare_stub_and_request(url, MODEL_NAME, creds=creds)

    numpy_input = numpy.zeros((1, 224, 224, 3), numpy.dtype('<f'))

    request.inputs[model_input].CopyFrom(
        tf.contrib.util.make_tensor_proto(numpy_input, shape=[1, 224, 224, 3]))

    with pytest.raises(grpc.RpcError) as context:
        stub.Predict(request, RPC_TIMEOUT)

    assert context.value.details() == 'Received http2 header with status: 403' 
開發者ID:IntelAI,項目名稱:inference-model-manager,代碼行數:22,代碼來源:test_inference_endpoints.py

示例8: test_handle_grpc_failure

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def test_handle_grpc_failure(self):
        """Raises non-retryable GoogleAdsFailures as GoogleAdsExceptions."""
        mock_error_message = _MOCK_FAILURE_VALUE

        class MockRpcErrorResponse(grpc.RpcError):
            def code(self):
                return grpc.StatusCode.INVALID_ARGUMENT

            def trailing_metadata(self):
                return ((interceptor._failure_key, mock_error_message),)

            def exception(self):
                return self

        interceptor = self._create_test_interceptor()

        self.assertRaises(GoogleAdsException,
                          interceptor._handle_grpc_failure,
                          MockRpcErrorResponse()) 
開發者ID:googleads,項目名稱:google-ads-python,代碼行數:21,代碼來源:exception_interceptor_test.py

示例9: test_handle_grpc_failure_not_google_ads_failure

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def test_handle_grpc_failure_not_google_ads_failure(self):
        """Raises as-is non-retryable non-GoogleAdsFailure exceptions."""
        class MockRpcErrorResponse(grpc.RpcError):
            def code(self):
                return grpc.StatusCode.INVALID_ARGUMENT

            def trailing_metadata(self):
                return (('bad-failure-key', 'arbitrary-value'),)

            def exception(self):
                return self

        interceptor = self._create_test_interceptor()

        self.assertRaises(MockRpcErrorResponse,
                          interceptor._handle_grpc_failure,
                          MockRpcErrorResponse()) 
開發者ID:googleads,項目名稱:google-ads-python,代碼行數:19,代碼來源:exception_interceptor_test.py

示例10: test_intercept_unary_unary_response_is_exception

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def test_intercept_unary_unary_response_is_exception(self):
        """If response.exception() is not None exception is handled."""
        mock_exception = grpc.RpcError()

        class MockResponse():
            def exception(self):
                return mock_exception

        mock_request = mock.Mock()
        mock_client_call_details = mock.Mock()
        mock_response = MockResponse()

        def mock_continuation(client_call_details, request):
            del client_call_details
            del request
            return mock_response

        interceptor = self._create_test_interceptor()

        with mock.patch.object(interceptor, '_handle_grpc_failure'):
            interceptor.intercept_unary_unary(
                mock_continuation, mock_client_call_details, mock_request)

            interceptor._handle_grpc_failure.assert_called_once_with(
                mock_response) 
開發者ID:googleads,項目名稱:google-ads-python,代碼行數:27,代碼來源:exception_interceptor_test.py

示例11: ping

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def ping(self, timeout=30):
        ft = grpc.channel_ready_future(self._channel)
        retry = self._max_retry
        try:
            while retry > 0:
                try:
                    ft.result(timeout=timeout)
                    return True
                except:
                    retry -= 1
                    LOGGER.debug("Retry connect addr <{}> {} times".format(self._uri, self._max_retry - retry))
                    if retry > 0:
                        continue
                    else:
                        LOGGER.error("Retry to connect server {} failed.".format(self._uri))
                        raise
        except grpc.FutureTimeoutError:
            raise NotConnectError('Fail connecting to server on {}. Timeout'.format(self._uri))
        except grpc.RpcError as e:
            raise NotConnectError("Connect error: <{}>".format(e))
        # Unexpected error
        except Exception as e:
            raise NotConnectError("Error occurred when trying to connect server:\n"
                                  "\t<{}>".format(str(e))) 
開發者ID:milvus-io,項目名稱:pymilvus,代碼行數:26,代碼來源:grpc_handler.py

示例12: is_grpc_error_unavailable

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def is_grpc_error_unavailable(e):
        is_grpc_error = isinstance(e, grpc.RpcError)
        if is_grpc_error and (e.code() == grpc.StatusCode.UNAVAILABLE):
            logging.error('grpc unavailable error: %s', e)
            return True
        return False 
開發者ID:warchildmd,項目名稱:google-assistant-hotword-raspi,代碼行數:8,代碼來源:assistant.py

示例13: test_send_coins

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def test_send_coins(self, alice):
        gen_and_sync_lnd(alice.bitcoin, [alice])
        alice.add_funds(alice.bitcoin, 1)
        p2wkh_address, np2wkh_address = get_addresses(alice)

        # test passes
        send1 = alice.send_coins(addr=p2wkh_address, amount=100000)
        generate(alice.bitcoin, 1)
        time.sleep(0.5)
        send2 = alice.send_coins(addr=np2wkh_address, amount=100000)

        assert isinstance(send1, rpc_pb2.SendCoinsResponse)
        assert isinstance(send2, rpc_pb2.SendCoinsResponse)

        # test failures
        pytest.raises(
            grpc.RpcError,
            lambda: alice.send_coins(
                alice.new_address(address_type="p2wkh").address, amount=100000 * -1
            ),
        )
        pytest.raises(
            grpc.RpcError,
            lambda: alice.send_coins(
                alice.new_address(address_type="p2wkh").address, amount=1000000000000000
            ),
        ) 
開發者ID:willcl-ark,項目名稱:lnd_grpc,代碼行數:29,代碼來源:test.py

示例14: test_stop_daemon

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def test_stop_daemon(self, node_factory):
        node = node_factory.get_node(implementation=LndNode, node_id="test_stop_node")
        node.daemon.wait_for_log("Server listening on")
        node.stop_daemon()
        # use is_in_log instead of wait_for_log as node daemon should be shutdown
        node.daemon.is_in_log("Shutdown complete")
        time.sleep(1)
        with pytest.raises(grpc.RpcError):
            node.get_info() 
開發者ID:willcl-ark,項目名稱:lnd_grpc,代碼行數:11,代碼來源:test.py

示例15: scb

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import RpcError [as 別名]
def scb(stub, wallet_password="", seed_words="", seed_password="", file_path_scb=""):
    with open(file_path_scb, 'rb') as f:
        content = f.read()
    scb_hex_str = binascii.hexlify(content)
    print(scb_hex_str)

    request = ln.InitWalletRequest(
        wallet_password=wallet_password.encode(),
        cipher_seed_mnemonic=[x.encode() for x in seed_words],
        recovery_window=5000,
        aezeed_passphrase=seed_password.encode(),
        channel_backups=scb_hex_str.encode()
    )

    try:
        response = stub.InitWallet(request)
    except grpc.RpcError as rpc_error_call:
        code = rpc_error_call.code()
        print(code, file=sys.stderr)
        details = rpc_error_call.details()
        print("err='RPCError InitWallet'")
        print("errMore=\"" + details + "\"")
        sys.exit(1)
    except:
        e = sys.exc_info()[0]
        print(e, file=sys.stderr)
        print("err='InitWallet'")
        sys.exit(1)

    # TODO(rootzoll) implement creating from seed/scb
    print("err='TODO: implement creating from seed/scb'")
    sys.exit(1) 
開發者ID:rootzoll,項目名稱:raspiblitz,代碼行數:34,代碼來源:lnd.initwallet.py


注:本文中的grpc.RpcError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。