Python grpc.insecure_channel() Examples
The following are 30
code examples of grpc.insecure_channel().
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: bookstore_client.py From python-docs-samples with Apache License 2.0 | 9 votes |
def run(host, port, api_key, auth_token, timeout, use_tls): """Makes a basic ListShelves call against a gRPC Bookstore server.""" if use_tls: with open('../roots.pem', 'rb') as f: creds = grpc.ssl_channel_credentials(f.read()) channel = grpc.secure_channel('{}:{}'.format(host, port), creds) else: channel = grpc.insecure_channel('{}:{}'.format(host, port)) stub = bookstore_pb2_grpc.BookstoreStub(channel) metadata = [] if api_key: metadata.append(('x-api-key', api_key)) if auth_token: metadata.append(('authorization', 'Bearer ' + auth_token)) shelves = stub.ListShelves(empty_pb2.Empty(), timeout, metadata=metadata) print('ListShelves: {}'.format(shelves))
Example #2
Source File: grpc_handler.py From pymilvus with Apache License 2.0 | 6 votes |
def _setup(self, host, port, uri, pre_ping=False): """ Create a grpc channel and a stub :raises: NotConnectError """ self._uri = set_uri(host, port, uri) self._channel = grpc.insecure_channel( self._uri, options=[(cygrpc.ChannelArgKey.max_send_message_length, -1), (cygrpc.ChannelArgKey.max_receive_message_length, -1), ('grpc.enable_retries', 1), ('grpc.keepalive_time_ms', 55000)] # (b'grpc.enable_http_proxy', 0)] ) self._stub = milvus_pb2_grpc.MilvusServiceStub(self._channel) self.status = Status()
Example #3
Source File: __init__.py From opentelemetry-python with Apache License 2.0 | 6 votes |
def __init__( self, endpoint=DEFAULT_ENDPOINT, service_name=None, host_name=None, client=None, ): self.endpoint = endpoint if client is None: self.channel = grpc.insecure_channel(self.endpoint) self.client = trace_service_pb2_grpc.TraceServiceStub( channel=self.channel ) else: self.client = client self.node = utils.get_node(service_name, host_name)
Example #4
Source File: test_perf_grpcio.py From purerpc with Apache License 2.0 | 6 votes |
def worker(port, queue, num_concurrent_streams, num_requests_per_stream, num_rounds, message_size, load_type): with grpc.insecure_channel("localhost:{}".format(port)) as channel: stub = GreeterStub(channel) if load_type == "unary": load_fn = do_load_unary else: raise ValueError(f"Unknown load type: {load_type}") for _ in range(num_rounds): start = time.time() task_results = Queue() for _ in range(num_concurrent_streams): load_fn(task_results, stub, num_requests_per_stream, message_size) results = [] for _ in range(num_concurrent_streams): results.append(task_results.get()) end = time.time() rps = num_concurrent_streams * num_requests_per_stream / (end - start) queue.put(rps) queue.put(results) queue.close() queue.join_thread()
Example #5
Source File: __init__.py From opentelemetry-python with Apache License 2.0 | 6 votes |
def __init__( self, endpoint: str = DEFAULT_ENDPOINT, service_name: str = None, host_name: str = None, client: metrics_service_pb2_grpc.MetricsServiceStub = None, ): self.endpoint = endpoint if client is None: channel = grpc.insecure_channel(self.endpoint) self.client = metrics_service_pb2_grpc.MetricsServiceStub( channel=channel ) else: self.client = client self.node = utils.get_node(service_name, host_name)
Example #6
Source File: route_guide_client.py From opentelemetry-python with Apache License 2.0 | 6 votes |
def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel("localhost:50051") as channel: channel = intercept_channel(channel, client_interceptor()) stub = route_guide_pb2_grpc.RouteGuideStub(channel) # Unary print("-------------- GetFeature --------------") guide_get_feature(stub) # Server streaming print("-------------- ListFeatures --------------") guide_list_features(stub) # Client streaming print("-------------- RecordRoute --------------") guide_record_route(stub) # Bidirectional streaming print("-------------- RouteChat --------------") guide_route_chat(stub)
Example #7
Source File: test_otcollector_trace_exporter.py From opentelemetry-python with Apache License 2.0 | 6 votes |
def test_constructor(self): mock_get_node = mock.Mock() patch = mock.patch( "opentelemetry.ext.opencensusexporter.util.get_node", side_effect=mock_get_node, ) service_name = "testServiceName" host_name = "testHostName" client = grpc.insecure_channel("") endpoint = "testEndpoint" with patch: exporter = OpenCensusSpanExporter( service_name=service_name, host_name=host_name, endpoint=endpoint, client=client, ) self.assertIs(exporter.client, client) self.assertEqual(exporter.endpoint, endpoint) mock_get_node.assert_called_with(service_name, host_name)
Example #8
Source File: test_utils.py From purerpc with Apache License 2.0 | 6 votes |
def grpc_channel(port_fixture_name, channel_arg_name="channel"): def decorator(func): if hasattr(func, "__parallelized__") and func.__parallelized__: raise TypeError("Cannot pass gRPC channel to already parallelized test, grpc_client_parallelize should " "be the last decorator in chain") @forge.compose( forge.copy(func), forge.modify(channel_arg_name, name=port_fixture_name, interface_name="port_fixture_value"), ) def new_func(*, port_fixture_value, **kwargs): import grpc with grpc.insecure_channel('127.0.0.1:{}'.format(port_fixture_value)) as channel: func(**kwargs, channel=channel) return new_func return decorator
Example #9
Source File: test_utils.py From purerpc with Apache License 2.0 | 6 votes |
def purerpc_channel(port_fixture_name, channel_arg_name="channel"): def decorator(corofunc): if not inspect.iscoroutinefunction(corofunc): raise TypeError("Expected coroutine function") @forge.compose( forge.copy(corofunc), forge.modify(channel_arg_name, name=port_fixture_name, interface_name="port_fixture_value"), ) async def new_corofunc(*, port_fixture_value, **kwargs): import purerpc async with purerpc.insecure_channel("127.0.0.1", port_fixture_value) as channel: await corofunc(**kwargs, channel=channel) return new_corofunc return decorator
Example #10
Source File: test_otcollector_metrics_exporter.py From opentelemetry-python with Apache License 2.0 | 6 votes |
def test_constructor(self): mock_get_node = mock.Mock() patch = mock.patch( "opentelemetry.ext.opencensusexporter.util.get_node", side_effect=mock_get_node, ) service_name = "testServiceName" host_name = "testHostName" client = grpc.insecure_channel("") endpoint = "testEndpoint" with patch: exporter = metrics_exporter.OpenCensusMetricsExporter( service_name=service_name, host_name=host_name, endpoint=endpoint, client=client, ) self.assertIs(exporter.client, client) self.assertEqual(exporter.endpoint, endpoint) mock_get_node.assert_called_with(service_name, host_name)
Example #11
Source File: nvml.py From integrations-extras with BSD 3-Clause "New" or "Revised" License | 6 votes |
def refresh_tags(self): channel = grpc.insecure_channel('unix://' + SOCKET_PATH) stub = PodResourcesListerStub(channel) response = stub.List(ListPodResourcesRequest()) new_tags = {} for pod_res in response.pod_resources: for container in pod_res.containers: for device in container.devices: if device.resource_name != "nvidia.com/gpu": continue pod_name = pod_res.name kube_namespace = pod_res.namespace kube_container_name = container.name for device_id in device.device_ids: # These are the tag names that datadog seems to use new_tags[device_id] = [ "pod_name:" + pod_name, "kube_namespace:" + kube_namespace, "kube_container_name:" + kube_container_name, ] with self.lock: self.known_tags = new_tags
Example #12
Source File: ende_client.py From OpenNMT-tf with MIT License | 6 votes |
def main(): parser = argparse.ArgumentParser(description="Translation client example") parser.add_argument("--model_name", required=True, help="model name") parser.add_argument("--sentencepiece_model", required=True, help="path to the sentence model") parser.add_argument("--host", default="localhost", help="model server host") parser.add_argument("--port", type=int, default=9000, help="model server port") parser.add_argument("--timeout", type=float, default=10.0, help="request timeout") args = parser.parse_args() channel = grpc.insecure_channel("%s:%d" % (args.host, args.port)) stub = prediction_service_pb2_grpc.PredictionServiceStub(channel) tokenizer = pyonmttok.Tokenizer("none", sp_model_path=args.sentencepiece_model) while True: text = input("Source: ") output = translate(stub, args.model_name, [text], tokenizer, timeout=args.timeout) print("Target: %s" % output[0]) print("")
Example #13
Source File: tiller.py From armada with Apache License 2.0 | 6 votes |
def get_channel(self): ''' Return a Tiller channel ''' tiller_ip = self._get_tiller_ip() tiller_port = self._get_tiller_port() try: LOG.debug( 'Tiller getting gRPC insecure channel at %s:%s ' 'with options: [grpc.max_send_message_length=%s, ' 'grpc.max_receive_message_length=%s]', tiller_ip, tiller_port, MAX_MESSAGE_LENGTH, MAX_MESSAGE_LENGTH) return grpc.insecure_channel( '%s:%s' % (tiller_ip, tiller_port), options=[ ('grpc.max_send_message_length', MAX_MESSAGE_LENGTH), ('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH) ]) except Exception: LOG.exception('Failed to initialize grpc channel to tiller.') raise ex.ChannelException()
Example #14
Source File: worker.py From neuroevolution with MIT License | 6 votes |
def __init__(self, env_name=ENVIRONMENT, strength=MUTATION_STRENGTH, host=HOST): """Creates a Worker instance. Args: env (string): The valid gym environment name. host (string): The hostname of the master server. strength (float): The genetic mutation strength. """ self.client = NeuroStub(grpc.insecure_channel(host)) self.env = gym.make(env_name) self.policy = Policy(self.env.action_space.n) self.strength = strength print("Host:", host) print("Environment:", env_name) print("Mutation Strength:", strength)
Example #15
Source File: sample_client_demo.py From python-grpc-demo with MIT License | 6 votes |
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)
Example #16
Source File: sample_client_demo_timeout.py From python-grpc-demo with MIT License | 6 votes |
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)
Example #17
Source File: tiller.py From armada with Apache License 2.0 | 6 votes |
def get_channel(self): ''' Return a Tiller channel ''' tiller_ip = self._get_tiller_ip() tiller_port = self._get_tiller_port() try: LOG.debug('Tiller getting gRPC insecure channel at %s:%s ' 'with options: [grpc.max_send_message_length=%s, ' 'grpc.max_receive_message_length=%s]', tiller_ip, tiller_port, MAX_MESSAGE_LENGTH, MAX_MESSAGE_LENGTH) return grpc.insecure_channel( '%s:%s' % (tiller_ip, tiller_port), options=[ ('grpc.max_send_message_length', MAX_MESSAGE_LENGTH), ('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH) ] ) except Exception: raise ex.ChannelException()
Example #18
Source File: tfs_sample_client.py From image-quality-assessment with Apache License 2.0 | 6 votes |
def get_image_quality_predictions(image_path, model_name): # Load and preprocess image image = utils.load_image(image_path, target_size=(224, 224)) image = keras.applications.mobilenet.preprocess_input(image) # Run through model target = f'{TFS_HOST}:{TFS_PORT}' channel = grpc.insecure_channel(target) stub = prediction_service_pb2_grpc.PredictionServiceStub(channel) request = predict_pb2.PredictRequest() request.model_spec.name = model_name request.model_spec.signature_name = 'image_quality' request.inputs['input_image'].CopyFrom( tf.contrib.util.make_tensor_proto(np.expand_dims(image, 0)) ) response = stub.Predict(request, 10.0) result = round(calc_mean_score(response.outputs['quality_prediction'].float_val), 2) print(json.dumps({'mean_score_prediction': np.round(result, 3)}, indent=2))
Example #19
Source File: sample_client_demo_timeout.py From python-grpc-demo with MIT License | 6 votes |
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)
Example #20
Source File: grpc_client_utils.py From inference-model-manager with Apache License 2.0 | 6 votes |
def prepare_stub_and_request(address, model_name, model_version=None, creds=None, opts=None, request_type=INFERENCE_REQUEST): if opts is not None: opts = (('grpc.ssl_target_name_override', opts),) if creds is not None: channel = grpc.secure_channel(address, creds, options=opts) else: channel = grpc.insecure_channel(address, options=opts) request = None stub = None if request_type == MODEL_STATUS_REQUEST: request = get_model_status_pb2.GetModelStatusRequest() stub = model_service_pb2_grpc.ModelServiceStub(channel) elif request_type == INFERENCE_REQUEST: stub = prediction_service_pb2_grpc.PredictionServiceStub(channel) request = predict_pb2.PredictRequest() request.model_spec.name = model_name if model_version is not None: request.model_spec.version.value = model_version return stub, request
Example #21
Source File: load_test_client.py From tpu_models with Apache License 2.0 | 6 votes |
def main(argv): del argv tpu_address = FLAGS.tpu if not any(pref in FLAGS.tpu for pref in ['http://', 'grpc://']): tpu_address = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu).master() tpu_address = '{}:{}'.format(tpu_address[:-len(':1234')], '8470' if FLAGS.grpc else '8473') tpu_address = tpu_address[len('abcd://'):] tf.logging.info('ModelServer at: {}'.format(tpu_address)) if FLAGS.grpc: grpc_channel = grpc.insecure_channel(tpu_address) stub = prediction_service_pb2_grpc.PredictionServiceStub(grpc_channel) run_grpc_load_test(FLAGS.num_requests, FLAGS.qps, generate_grpc_request(), stub) else: payload = generate_rest_payload() run_rest_load_test(FLAGS.num_requests, FLAGS.qps, tpu_address, payload)
Example #22
Source File: trivial_client.py From python-grpc with Apache License 2.0 | 5 votes |
def run(): parser = argparse.ArgumentParser() parser.add_argument( '--log_payloads', action='store_true', help='log request/response objects to open-tracing spans') args = parser.parse_args() config = Config( config={ 'sampler': { 'type': 'const', 'param': 1, }, 'logging': True, }, service_name='trivial-client') tracer = config.initialize_tracer() tracer_interceptor = open_tracing_client_interceptor( tracer, log_payloads=args.log_payloads) channel = grpc.insecure_channel('localhost:50051') channel = intercept_channel(channel, tracer_interceptor) stub = command_line_pb2.CommandLineStub(channel) response = stub.Echo(command_line_pb2.CommandRequest(text='Hello, hello')) print(response.text) time.sleep(2) tracer.close() time.sleep(2)
Example #23
Source File: test_server_interceptor.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def test_span_lifetime(self): """Check that the span is active for the duration of the call.""" interceptor = server_interceptor() # To capture the current span at the time the handler is called active_span_in_handler = None def handler(request, context): nonlocal active_span_in_handler active_span_in_handler = trace.get_current_span() return b"" server = grpc.server( futures.ThreadPoolExecutor(max_workers=1), options=(("grpc.so_reuseport", 0),), ) server = intercept_server(server, interceptor) server.add_generic_rpc_handlers((UnaryUnaryRpcHandler(handler),)) port = server.add_insecure_port("[::]:0") channel = grpc.insecure_channel("localhost:{:d}".format(port)) active_span_before_call = trace.get_current_span() try: server.start() channel.unary_unary("")(b"") finally: server.stop(None) active_span_after_call = trace.get_current_span() self.assertIsNone(active_span_before_call) self.assertIsNone(active_span_after_call) self.assertIsInstance(active_span_in_handler, trace_sdk.Span) self.assertIsNone(active_span_in_handler.parent)
Example #24
Source File: client_wrapper.py From python-grpc-demo with MIT License | 5 votes |
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
Example #25
Source File: test_server_interceptor.py From opentelemetry-python with Apache License 2.0 | 5 votes |
def test_sequential_server_spans(self): """Check that sequential RPCs get separate server spans.""" interceptor = server_interceptor() # Capture the currently active span in each thread active_spans_in_handler = [] def handler(request, context): active_spans_in_handler.append(trace.get_current_span()) return b"" server = grpc.server( futures.ThreadPoolExecutor(max_workers=1), options=(("grpc.so_reuseport", 0),), ) server = intercept_server(server, interceptor) server.add_generic_rpc_handlers((UnaryUnaryRpcHandler(handler),)) port = server.add_insecure_port("[::]:0") channel = grpc.insecure_channel("localhost:{:d}".format(port)) try: server.start() channel.unary_unary("")(b"") channel.unary_unary("")(b"") finally: server.stop(None) self.assertEqual(len(active_spans_in_handler), 2) # pylint:disable=unbalanced-tuple-unpacking span1, span2 = active_spans_in_handler # Spans should belong to separate traces, and each should be a root # span self.assertNotEqual(span1.context.span_id, span2.context.span_id) self.assertNotEqual(span1.context.trace_id, span2.context.trace_id) self.assertIsNone(span1.parent) self.assertIsNone(span1.parent)
Example #26
Source File: clusterspecgenerator_client.py From hops-tensorflow with Apache License 2.0 | 5 votes |
def __init__(self, target): self.channel = grpc.insecure_channel(target) self.stub = csg_grpc.ClusterSpecGeneratorStub(self.channel)
Example #27
Source File: channel.py From aiogrpc with Apache License 2.0 | 5 votes |
def insecure_channel(target, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): """Creates an insecure Channel to a server. Args: target: The server address options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object. """ return Channel(_grpc.insecure_channel(target, options), loop, executor, standalone_pool_for_streaming)
Example #28
Source File: grpc_client.py From xos with Apache License 2.0 | 5 votes |
def __init__(self, hostname, port=50055): super(InsecureClient, self).__init__(hostname, port) self.channel = grpc.insecure_channel("%s:%d" % (self.hostname, self.port)) self.stub = xos_pb2_grpc.xosStub(self.channel) self.modeldefs = modeldefs_pb2_grpc.modeldefsStub(self.channel) self.utility = utility_pb2_grpc.utilityStub(self.channel) self.xos_orm = orm.ORMStub(self.stub, "xos")
Example #29
Source File: conftest.py From model_server with Apache License 2.0 | 5 votes |
def create_grpc_channel(): def _create_channel(address: str, service: int): channel = grpc.insecure_channel(address) if service == MODEL_SERVICE: return model_service_pb2_grpc.ModelServiceStub(channel) elif service == PREDICTION_SERVICE: return prediction_service_pb2_grpc.PredictionServiceStub(channel) return None return _create_channel
Example #30
Source File: cs3iface.py From wopiserver with Apache License 2.0 | 5 votes |
def init(config, log): '''Init module-level variables''' ctx['log'] = log ctx['chunksize'] = config.getint('io', 'chunksize') ctx['authtokenvalidity'] = config.getint('cs3', 'authtokenvalidity') revahost = config.get('cs3', 'revahost') # prepare the gRPC connection ch = grpc.insecure_channel(revahost) ctx['cs3stub'] = cs3gw_grpc.GatewayAPIStub(ch)