当前位置: 首页>>代码示例>>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;未经允许,请勿转载。