当前位置: 首页>>代码示例>>Python>>正文


Python grpc.channel_ready_future方法代码示例

本文整理汇总了Python中grpc.channel_ready_future方法的典型用法代码示例。如果您正苦于以下问题:Python grpc.channel_ready_future方法的具体用法?Python grpc.channel_ready_future怎么用?Python grpc.channel_ready_future使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在grpc的用法示例。


在下文中一共展示了grpc.channel_ready_future方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ping

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [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

示例2: run

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def run():
    channel = grpc.insecure_channel('localhost:50051')
    try:
        grpc.channel_ready_future(channel).result(timeout=10)
    except grpc.FutureTimeoutError:
        sys.exit('Error connecting to server')
    else:
        stub = users_service.UsersStub(channel)
        metadata = [('ip', '127.0.0.1')]
        response = stub.CreateUser(
            users_messages.CreateUserRequest(username='tom'),
            metadata=metadata,
        )
        if response:
            print("User created:", response.user.username)
        request = users_messages.GetUsersRequest(
            user=[users_messages.User(username="alexa", user_id=1),
                  users_messages.User(username="christie", user_id=1)]
        )
        response = stub.GetUsers(request, timeout=0.00001)
        for resp in response:
            print(resp) 
开发者ID:amitsaha,项目名称:python-grpc-demo,代码行数:24,代码来源:sample_client_demo_timeout.py

示例3: run

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def run():
    channel = grpc.insecure_channel('localhost:50051')
    try:
        grpc.channel_ready_future(channel).result(timeout=10)
    except grpc.FutureTimeoutError:
        sys.exit('Error connecting to server')
    else:
        stub = users_service.UsersStub(channel)
        metadata = [('ip', '127.0.0.1')]
        response = stub.CreateUser(
            users_messages.CreateUserRequest(username='tom'),
            metadata=metadata,
        )
        if response:
            print("User created:", response.user.username)
        request = users_messages.GetUsersRequest(
            user=[users_messages.User(username="alexa", user_id=1),
                  users_messages.User(username="christie", user_id=1)]
        )
        response = stub.GetUsers(request)
        for resp in response:
            print(resp) 
开发者ID:amitsaha,项目名称:python-grpc-demo,代码行数:24,代码来源:sample_client_demo.py

示例4: connect

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def connect(cls, datadir, jarfile):
        # Check for running server instances
        jar = os.path.split(jarfile)[-1]
        for p in psutil.process_iter(attrs = ["name", "cmdline"]):
            if (p.info["name"] == "java" and
                any(x.endswith(jar) for x in p.info["cmdline"])):
                return

        # Start server
        cmdline = ["java", "-Xmx2G", "-XX:+UseG1GC", "-jar",
                   jarfile, str(cls.rpc_port), datadir]
        cls.rpc_server_proc = psutil.Popen(cmdline)

        atexit.register(RemoteServer.disconnect)
        with grpc.insecure_channel(cls.rpc_uri) as chan:
            grpc.channel_ready_future(chan).result(timeout = 60.0) 
开发者ID:ut-astria,项目名称:orbdetpy,代码行数:18,代码来源:server.py

示例5: reset

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def reset(self):
    if self._channel is not None:
      # Client surrenders in the current game and starts next one.

      self._channel.close()
      self._channel = None

    # Get game server address and side id from master.
    start_game_request = master_pb2.StartGameRequest(
        game_version=config.game_version, username=self._username,
        token=self._token, model_name=self._model_name,
        include_rendering=self._include_rendering)
    response = self._reset_with_retries(start_game_request)
    self._game_id = response.game_id
    self._channel = utils.get_grpc_channel(response.game_server_address)
    grpc.channel_ready_future(self._channel).result()
    get_env_result_request = game_server_pb2.GetEnvResultRequest(
        game_version=config.game_version, game_id=self._game_id,
        username=self._username, token=self._token, model_name=self._model_name)
    return self._get_env_result(get_env_result_request, 'GetEnvResult')[0] 
开发者ID:google-research,项目名称:football,代码行数:22,代码来源:remote_football_env.py

示例6: user_authentication

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def user_authentication(session_id: bytes, cert: bytes, ip: str, name: str) -> str:
    # Pin the robot certificate for opening the channel
    creds = grpc.ssl_channel_credentials(root_certificates=cert)

    print("Attempting to download guid from {} at {}:443...".format(
        colored(name, "cyan"), colored(ip, "cyan")), end="")
    sys.stdout.flush()
    channel = grpc.secure_channel("{}:443".format(ip), creds,
                                  options=(("grpc.ssl_target_name_override", name,),))

    # Verify the connection to Vector is able to be established (client-side)
    try:
        # Explicitly grab _channel._channel to test the underlying grpc channel directly
        grpc.channel_ready_future(channel).result(timeout=15)
    except grpc.FutureTimeoutError:
        print(colored(" ERROR", "red"))
        sys.exit("\nUnable to connect to Vector\n"
                 "Please be sure to connect via the Vector companion app first, and connect your computer to the same network as your Vector.")

    try:
        interface = messaging.client.ExternalInterfaceStub(channel)
        request = messaging.protocol.UserAuthenticationRequest(
            user_session_id=session_id.encode('utf-8'),
            client_name=socket.gethostname().encode('utf-8'))
        response = interface.UserAuthentication(request)
        if response.code != messaging.protocol.UserAuthenticationResponse.AUTHORIZED:  # pylint: disable=no-member
            print(colored(" ERROR", "red"))
            sys.exit("\nFailed to authorize request:\n"
                     "Please be sure to first set up Vector using the companion app.")
    except grpc.RpcError as e:
        print(colored(" ERROR", "red"))
        sys.exit("\nFailed to authorize request:\n"
                 "An unknown error occurred '{}'".format(e))

    print(colored(" DONE\n", "green"))
    return response.client_token_guid 
开发者ID:rmountjoy92,项目名称:VectorCloud,代码行数:38,代码来源:configure.py

示例7: _check_grpc_channel_ready

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def _check_grpc_channel_ready(channel):
  """Helper function to check the gRPC channel is ready N times."""
  for _ in range(_MAX_CONNECTION_ATTEMPTS - 1):
    try:
      return grpc.channel_ready_future(channel).result(timeout=1)
    except grpc.FutureTimeoutError:
      pass
  return grpc.channel_ready_future(channel).result(timeout=1) 
开发者ID:deepmind,项目名称:dm_memorytasks,代码行数:10,代码来源:_load_environment.py

示例8: run

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def run():
    # read in certificate
    with open('server.crt') as f:
        trusted_certs = f.read().encode()

    # create credentials
    credentials = grpc.ssl_channel_credentials(root_certificates=trusted_certs)
    channel = grpc.secure_channel('localhost:50051', credentials)
    try:
        grpc.channel_ready_future(channel).result(timeout=10)
    except grpc.FutureTimeoutError:
        sys.exit('Error connecting to server')
    else:
        stub = users_service.UsersStub(channel)
        metadata = [('ip', '127.0.0.1')]

        try:
            response = stub.CreateUser(
                users_messages.CreateUserRequest(username='tom'),
                metadata=metadata,
            )
        except grpc.RpcError as e:
            print('CreateUser failed with {0}: {1}'.format(e.code(), e.details()))
        else:
            print("User created:", response.user.username)

        request = users_messages.GetUsersRequest(
            user=[users_messages.User(username="alexa", user_id=1),
                  users_messages.User(username="christie", user_id=1)]
        )
        response = stub.GetUsers(request)
        for resp in response:
            print(resp) 
开发者ID:amitsaha,项目名称:python-grpc-demo,代码行数:35,代码来源:sample_client_demo.py

示例9: __init__

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def __init__(self, service_module, stub_name, host, port, timeout=10):
        channel = grpc.insecure_channel('{0}:{1}'.format(host, port))
        try:
            grpc.channel_ready_future(channel).result(timeout=10)
        except grpc.FutureTimeoutError:
            sys.exit('Error connecting to server')
        self.stub = getattr(service_module, stub_name)(channel)
        self.timeout = timeout 
开发者ID:amitsaha,项目名称:python-grpc-demo,代码行数:10,代码来源:client_wrapper.py

示例10: _report_join

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def _report_join(self, ips):
        for ip in ips:
            channel = grpc.insecure_channel(
                "{ip}:{port}".format(ip=ip, port=self._port)
            )
            try:
                grpc.channel_ready_future(channel).result(timeout=2)
            except Exception as e:
                logging.warning(str(e))
                return False
            else:
                stub = communicate_pb2_grpc.ReportStub(channel)
            try:
                response = stub.GetGroupStatus(
                    communicate_pb2.GroupStatusRequest(), timeout=2
                )
            except Exception as e:
                logging.warning(str(e))
            else:
                logging.info("counter retreived")
                self._count = response.counter
                self._io_tool.register_ip(
                    SharedStorage.ip_address, self._count
                )
                return True
        logging.warning("counter not retreived")
        self._io_tool.register_ip(SharedStorage.ip_address, self._count)
        return False 
开发者ID:caicloud,项目名称:ftlib,代码行数:30,代码来源:impl.py

示例11: _update_master

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def _update_master(self):
    while True:
      try:
        master_address = utils.get_master_address(self._track)
        logging.info('Connecting to %s', master_address)
        self._master_channel = utils.get_grpc_channel(master_address)
        grpc.channel_ready_future(self._master_channel).result(timeout=10)
        break
      except grpc.FutureTimeoutError:
        logging.info('Failed to connect to master')
      except BaseException as e:
        logging.info('Error %s, sleeping 10 secs', e)
        time.sleep(10)
    logging.info('Connection successful') 
开发者ID:google-research,项目名称:football,代码行数:16,代码来源:remote_football_env.py

示例12: main

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def main(config):
    """Train an ES policy."""
    if config.run_on_gke:
        servers = ['{}'.format(addr)
                   for addr in config.server_addresses.split(',')]
    else:
        servers = ['127.0.0.1:{}'.format(config.server_port + i)
                   for i in range(config.num_workers)]
    print(servers)
    stubs = []
    for server in servers:
        if config.run_on_gke:
            channel = grpc.insecure_channel(
                server, [('grpc.lb_policy_name', 'round_robin')])
        else:
            channel = grpc.insecure_channel(server)
        grpc.channel_ready_future(channel).result()
        stubs.append(evaluation_service_pb2_grpc.RolloutStub(channel))

    learner.ESLearner(
        logdir=config.logdir,
        config=config.config,
        stubs=stubs,
    ).train()

    # This is to prevent GKE from restarting pod when the job finishes.
    if config.run_on_gke:
        try:
            while True:
                time.sleep(_ONE_DAY_IN_SECONDS)
        except KeyboardInterrupt:
            print('Job done.') 
开发者ID:lerrytang,项目名称:es_on_gke,代码行数:34,代码来源:es_master.py

示例13: do_state_init

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def do_state_init(self, event):
        # Initialize gRPC
        self.channel = grpc.insecure_channel(self.host_and_port)
        self.channel_ready_future = grpc.channel_ready_future(self.channel)

        self.log.info('openolt-device-created') 
开发者ID:opencord,项目名称:voltha,代码行数:8,代码来源:openolt_device.py

示例14: set_uri

# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import channel_ready_future [as 别名]
def set_uri(host, port, uri):
    if host is not None:
        _port = port if port is not None else config.GRPC_PORT
        _host = host
    elif port is None:
        try:
            _uri = urlparse(uri) if uri else urlparse(config.GRPC_URI)
            _host = _uri.hostname
            _port = _uri.port
        except (AttributeError, ValueError, TypeError) as e:
            raise ParamError("uri is illegal: {}".format(e))
    else:
        raise ParamError("Param is not complete. Please invoke as follow:\n"
                         "\t(host = ${HOST}, port = ${PORT})\n"
                         "\t(uri = ${URI})\n")

    if not is_legal_host(_host) or not is_legal_port(_port):
        raise ParamError("host or port is illeagl")

    return "{}:{}".format(str(_host), str(_port))


# def connect(addr, timeout):
#     channel = grpc.insecure_channel(
#         addr,
#         options=[(cygrpc.ChannelArgKey.max_send_message_length, -1),
#                  (cygrpc.ChannelArgKey.max_receive_message_length, -1)]
#     )
#     try:
#         ft = grpc.channel_ready_future(channel)
#         ft.result(timeout=timeout)
#         return True
#     except grpc.FutureTimeoutError:
#         raise NotConnectError('Fail connecting to server on {}. Timeout'.format(addr))
#     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)))
#     finally:
#         ft.cancel()
#         ft.__del__()
#         channel.__del__() 
开发者ID:milvus-io,项目名称:pymilvus,代码行数:46,代码来源:grpc_handler.py


注:本文中的grpc.channel_ready_future方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。