本文整理汇总了Python中grpc.FutureTimeoutError方法的典型用法代码示例。如果您正苦于以下问题:Python grpc.FutureTimeoutError方法的具体用法?Python grpc.FutureTimeoutError怎么用?Python grpc.FutureTimeoutError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类grpc
的用法示例。
在下文中一共展示了grpc.FutureTimeoutError方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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)
示例2: run
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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)
示例3: ping
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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)))
示例4: test_create_collection_exception
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [as 别名]
def test_create_collection_exception(self, gcon):
collection_param = {
"collection_name": "test_create_collection_exceptions",
"dimension": 128,
"metric_type": MetricType.L2,
"index_file_size": 10
}
mock_grpc_timeout = mock.MagicMock(side_effect=grpc.FutureTimeoutError())
with mock.patch.object(Uum, 'future', mock_grpc_timeout):
status = gcon.create_collection(collection_param)
assert not status.OK()
mock_grpc_error = mock.MagicMock(side_effect=MockGrpcError())
with mock.patch.object(Uum, 'future', mock_grpc_error):
status = gcon.create_collection(collection_param)
assert not status.OK()
mock_exception = mock.MagicMock(side_effect=Exception("error"))
with mock.patch.object(Uum, 'future', mock_exception):
status = gcon.create_collection(collection_param)
assert not status.OK()
示例5: user_authentication
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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
示例6: _check_grpc_channel_ready
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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)
示例7: run
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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)
示例8: __init__
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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
示例9: error_handler
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [as 别名]
def error_handler(*rargs):
def wrapper(func):
def handler(self, *args, **kwargs):
record_dict = {}
try:
record_dict["API start"] = str(datetime.datetime.now())
if self._pre_ping:
self.ping()
record_dict["RPC start"] = str(datetime.datetime.now())
return func(self, *args, **kwargs)
except grpc.FutureTimeoutError as e:
record_dict["RPC timeout"] = str(datetime.datetime.now())
LOGGER.error("\nAddr [{}] {}\nRequest timeout: {}\n\t{}".format(self.server_address, func.__name__, e, record_dict))
status = Status(Status.UNEXPECTED_ERROR, message='Request timeout')
return status if not rargs else tuple([status]) + rargs
except grpc.RpcError as e:
record_dict["RPC error"] = str(datetime.datetime.now())
LOGGER.error("\nAddr [{}] {}\nRpc error: {}\n\t{}".format(self.server_address, func.__name__, e, record_dict))
status = Status(e.code(), message='Error occurred. {}'.format(e.details()))
return status if not rargs else tuple([status]) + rargs
except Exception as e:
record_dict["Exception"] = str(datetime.datetime.now())
LOGGER.error("\nAddr [{}] {}\nExcepted error: {}\n\t{}".format(self.server_address, func.__name__, e, record_dict))
status = Status(Status.UNEXPECTED_ERROR, message=str(e))
return status if not rargs else tuple([status]) + rargs
return handler
return wrapper
示例10: _update_master
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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')
示例11: set_uri
# 需要导入模块: import grpc [as 别名]
# 或者: from grpc import FutureTimeoutError [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__()