Python grpc.secure_channel() Examples

The following are 30 code examples of grpc.secure_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 vote down vote up
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: Tbon.py    From pcocc with GNU General Public License v3.0 8 votes vote down vote up
def __init__(self, connect_info):

        self._vmid = connect_info[0]
        self._host = connect_info[1]
        self._port = connect_info[2]
        self._stub = None
        self._channel = None

        client_cert = Config().batch.client_cert
        credential = grpc.ssl_channel_credentials(
            root_certificates=client_cert.ca_cert,
            private_key=client_cert.key,
            certificate_chain=client_cert.cert
        )
        self._channel = grpc.secure_channel(
            self._host + ":" + self._port, credential)

        self._stub = agent_pb2_grpc.pcoccNodeStub(self._channel) 
Example #3
Source File: grpc_client_utils.py    From inference-model-manager with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: ex4_getText2VoiceStream.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceStream(inText,inFileName):

	channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
	stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

	message = gigagenieRPC_pb2.reqText()
	message.lang=0
	message.mode=0
	message.text=inText
	writeFile=open(inFileName,'wb')
	for response in stub.getText2VoiceStream(message):
		if response.HasField("resOptions"):
			print ("\n\nResVoiceResult: %d" %(response.resOptions.resultCd))
		if response.HasField("audioContent"):
			print ("Audio Stream\n\n")
			writeFile.write(response.audioContent)
	writeFile.close()
	return response.resOptions.resultCd 
Example #5
Source File: ex3_getText2VoiceUrl.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceUrl(inText):

	channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
	stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

	message = gigagenieRPC_pb2.reqText()
	message.lang=0
	message.mode=0
	message.text=inText
	response = stub.getText2VoiceUrl(message)

	print ("\n\nresultCd: %d" % (response.resultCd))
	if response.resultCd == 200:
		print ("TTS 생성에 성공하였습니다.\n\n\n아래 URL을 웹브라우져에 넣어보세요.")
		print ("Stream Url: %s\n\n" % (response.url))
	else:
		print ("TTS 생성에 실패하였습니다.")
		print ("Fail: %d" % (response.resultCd)) 
Example #6
Source File: ex2_getVoice2Text.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getVoice2Text():    

    print ("Ctrl+\ to quit ...")
    
    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)
    request = generate_request()
    resultText = ''
    for response in stub.getVoice2Text(request):
        if response.resultCd == 200: # partial
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
        elif response.resultCd == 201: # final
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
            break
        else:
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            break

    print ("TEXT: %s" % (resultText))
    return resultText 
Example #7
Source File: ex2_getVoice2Text.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getVoice2Text():	
    print ("\n\n음성인식을 시작합니다.\n\n종료하시려면 Ctrl+\ 키를 누루세요.\n\n\n")
	
    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)
    request = generate_request()
    resultText = ''
    for response in stub.getVoice2Text(request):
        if response.resultCd == 200: # partial
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
        elif response.resultCd == 201: # final
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
            break
        else:
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            break

    print ("\n\n인식결과: %s \n\n\n" % (resultText).encode('utf-8'))
    return resultText 
Example #8
Source File: application.py    From python-app-sdk with MIT License 6 votes vote down vote up
def __init__(self, app_id, access_key,
                 handler_address="", cert_content="",
                 discovery_address="discovery.thethings.network:1900"):
        self.app_id = app_id
        self.app_access_key = access_key

        if not handler_address:
            discovery = DiscoveryClient(discovery_address)
            announcement = discovery.get_by_app_id(self.app_id.encode())
            handler_address = announcement.net_address
            cert_content = announcement.certificate
        elif not cert_content:
            raise RuntimeError("You need to provide credentials")

        creds = grpc.ssl_channel_credentials(cert_content.encode())
        channel = grpc.secure_channel(handler_address, creds)
        self.client = handler.ApplicationManagerStub(channel) 
Example #9
Source File: client.py    From predixpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _init_channel(self):
        """
        build the grpc channel used for both publisher and subscriber
        :return: None
        """
        host = self._get_host()
        port = self._get_grpc_port()

        if 'TLS_PEM_FILE' in os.environ:
            with open(os.environ['TLS_PEM_FILE'], mode='rb') as f:  # b is important -> binary
                file_content = f.read()
            credentials = grpc.ssl_channel_credentials(root_certificates=file_content)
        else:
            credentials = grpc.ssl_channel_credentials()

        self._channel = grpc.secure_channel(host + ":" + port, credentials=credentials)
        self._init_health_checker() 
Example #10
Source File: grpc_util_test.py    From tensorboard with Apache License 2.0 6 votes vote down vote up
def run(self):
        """Context manager to run the gRPC server and yield a client for it."""
        server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
        grpc_util_test_pb2_grpc.add_TestServiceServicer_to_server(self, server)
        port = server.add_secure_port(
            "localhost:0", grpc.local_server_credentials()
        )

        def launch_server():
            server.start()
            server.wait_for_termination()

        thread = threading.Thread(target=launch_server, name="TestGrpcServer")
        thread.daemon = True
        thread.start()
        with grpc.secure_channel(
            "localhost:%d" % port, grpc.local_channel_credentials()
        ) as channel:
            yield grpc_util_test_pb2_grpc.TestServiceStub(channel)
        server.stop(grace=None)
        thread.join() 
Example #11
Source File: lnd.initwallet.py    From raspiblitz with MIT License 6 votes vote down vote up
def main():
    os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
    cert = open('/mnt/hdd/lnd/tls.cert', 'rb').read()
    ssl_creds = grpc.ssl_channel_credentials(cert)
    channel = grpc.secure_channel('localhost:10009', ssl_creds)
    stub = lnrpc.WalletUnlockerStub(channel)

    wallet_password, seed_words, seed_password, file_path_scb = parse_args()

    if mode == "new":
        print("# *** CREATING NEW LND WALLET ***")
        new(stub, wallet_password)

    elif mode == "seed":
        print("# *** RECOVERING LND WALLET FROM SEED ***")
        seed(stub, wallet_password, seed_words, seed_password)

    elif mode == "scb":
        print("# *** RECOVERING LND WALLET FROM SEED + SCB ***")
        scb(stub, wallet_password, seed_words, seed_password, file_path_scb) 
Example #12
Source File: blitz.ip2tor.py    From raspiblitz with MIT License 6 votes vote down vote up
def lndPayInvoice(lnInvoiceString):
    try:
        # call LND GRPC API
        macaroon = codecs.encode(open(LND_ADMIN_MACAROON_PATH, 'rb').read(), 'hex')
        os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
        cert = open(LND_TLS_PATH, 'rb').read()
        ssl_creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel("{0}:10009".format(LND_IP), ssl_creds)
        stub = rpcstub.LightningStub(channel)
        request = lnrpc.SendRequest(
            payment_request=lnInvoiceString,
        )
        response = stub.SendPaymentSync(request, metadata=[('macaroon', macaroon)])

        # validate results
        if len(response.payment_error) > 0:
            print("error='PAYMENT FAILED'")
            print("error_detail='{}'".format(response.payment_error))
            return  

    except Exception as e:
       print("error='FAILED LND INVOICE PAYMENT'")
       return

    return response 
Example #13
Source File: blitz.ip2tor.py    From raspiblitz with MIT License 6 votes vote down vote up
def lndDecodeInvoice(lnInvoiceString):
    try:
        # call LND GRPC API
        macaroon = codecs.encode(open(LND_ADMIN_MACAROON_PATH, 'rb').read(), 'hex')
        os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
        cert = open(LND_TLS_PATH, 'rb').read()
        ssl_creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel("{0}:10009".format(LND_IP), ssl_creds)
        stub = rpcstub.LightningStub(channel)
        request = lnrpc.PayReqString(
            pay_req=lnInvoiceString,
        )
        response = stub.DecodePayReq(request, metadata=[('macaroon', macaroon)])

        # validate results
        if response.num_msat <= 0:
            print("error='ZERO INVOICES NOT ALLOWED'")
            return  

    except Exception as e:
        print("error='FAILED LND INVOICE DECODING'")
        return

    return response 
Example #14
Source File: ex4_getText2VoiceStream.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceStream(inText,inFileName):

    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

    message = gigagenieRPC_pb2.reqText()
    message.lang=0
    message.mode=0
    message.text=inText
    writeFile=open(inFileName,'wb')
    for response in stub.getText2VoiceStream(message):
        if response.HasField("resOptions"):
            print ("ResVoiceResult: %d" %(response.resOptions.resultCd))
        if response.HasField("audioContent"):
            print ("Audio Stream")
            writeFile.write(response.audioContent)
    writeFile.close() 
Example #15
Source File: ex4_getText2VoiceStream.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceStream(inText,inFileName):

    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

    message = gigagenieRPC_pb2.reqText()
    message.lang=0
    message.mode=0
    message.text=inText
    writeFile=open(inFileName,'wb')
    for response in stub.getText2VoiceStream(message):
        if response.HasField("resOptions"):
            print ("ResVoiceResult: %d" %(response.resOptions.resultCd))
        if response.HasField("audioContent"):
            print ("Audio Stream")
            writeFile.write(response.audioContent)
    writeFile.close() 
Example #16
Source File: ex2_getVoice2Text.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getVoice2Text():	

    print ("Ctrl+\ to quit ...")
	
    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)
    request = generate_request()
    resultText = ''
    for response in stub.getVoice2Text(request):
        if response.resultCd == 200: # partial
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
        elif response.resultCd == 201: # final
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
            break
        else:
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            break

    print ("TEXT: %s" % (resultText))
    return resultText 
Example #17
Source File: ex4_getText2VoiceStream.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceStream(inText,inFileName):

    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

    message = gigagenieRPC_pb2.reqText()
    message.lang=0
    message.mode=0
    message.text=inText
    writeFile=open(inFileName,'wb')
    for response in stub.getText2VoiceStream(message):
        if response.HasField("resOptions"):
            print ("ResVoiceResult: %d" %(response.resOptions.resultCd))
        if response.HasField("audioContent"):
            print ("Audio Stream")
            writeFile.write(response.audioContent)
    writeFile.close() 
Example #18
Source File: ex4_getText2VoiceStream.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceStream(inText,inFileName):

	channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), UA.getCredentials())
	stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

	message = gigagenieRPC_pb2.reqText()
	message.lang=0
	message.mode=0
	message.text=inText
	writeFile=open(inFileName,'wb')
	for response in stub.getText2VoiceStream(message):
		if response.HasField("resOptions"):
			print ("\n\nResVoiceResult: %d" %(response.resOptions.resultCd))
		if response.HasField("audioContent"):
			print ("Audio Stream\n\n")
			writeFile.write(response.audioContent)
	writeFile.close()
	return response.resOptions.resultCd 
Example #19
Source File: ex2_getVoice2Text.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getVoice2Text():	
    print ("\n\n음성인식을 시작합니다.\n\n종료하시려면 Ctrl+\ 키를 누루세요.\n\n\n")
    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), UA.getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)
    request = generate_request()
    resultText = ''
    for response in stub.getVoice2Text(request):
        if response.resultCd == 200: # partial
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
        elif response.resultCd == 201: # final
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
            break
        else:
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            break

    print ("\n\n인식결과: %s \n\n\n" % (resultText))
    return resultText 
Example #20
Source File: ex5_queryText.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def queryByText(text):

	channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), UA.getCredentials())
	stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

	message = gigagenieRPC_pb2.reqQueryText()
	message.queryText = text
	message.userSession = "1234"
	message.deviceId = "yourdevice"
		
	response = stub.queryByText(message)

	print ("\n\nresultCd: %d" % (response.resultCd))
	if response.resultCd == 200:
		print ("\n\n\n질의한 내용: %s" % (response.uword))
		#dssAction = response.action
		for a in response.action:
			response = a.mesg
		parsing_resp = response.replace('<![CDATA[', '')
		parsing_resp = parsing_resp.replace(']]>', '')
		print("\n\n질의에 대한 답변: " + parsing_resp + '\n\n\n')
		#return response.url
	else:
		print ("Fail: %d" % (response.resultCd))
		#return None 
Example #21
Source File: ex3_getText2VoiceUrl.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceUrl(inText):

	channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), UA.getCredentials())
	stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

	message = gigagenieRPC_pb2.reqText()
	message.lang=0
	message.mode=0
	message.text=inText
	response = stub.getText2VoiceUrl(message)

	print ("\n\nresultCd: %d" % (response.resultCd))
	if response.resultCd == 200:
		print ("TTS 생성에 성공하였습니다.\n\n\n아래 URL을 웹브라우져에 넣어보세요.")
		print ("Stream Url: %s\n\n" % (response.url))
	else:
		print ("TTS 생성에 실패하였습니다.")
		print ("Fail: %d" % (response.resultCd)) 
Example #22
Source File: ex4_getText2VoiceStream.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceStream(inText,inFileName):

    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

    message = gigagenieRPC_pb2.reqText()
    message.lang=0
    message.mode=0
    message.text=inText
    writeFile=open(inFileName,'wb')
    for response in stub.getText2VoiceStream(message):
        if response.HasField("resOptions"):
            print ("ResVoiceResult: %d" %(response.resOptions.resultCd))
        if response.HasField("audioContent"):
            print ("Audio Stream")
            writeFile.write(response.audioContent)
    writeFile.close() 
Example #23
Source File: ex2_getVoice2Text.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getVoice2Text():    

    print ("Ctrl+\ to quit ...")
    
    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)
    request = generate_request()
    resultText = ''
    for response in stub.getVoice2Text(request):
        if response.resultCd == 200: # partial
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
        elif response.resultCd == 201: # final
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
            break
        else:
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            break

    print ("TEXT: %s" % (resultText))
    return resultText 
Example #24
Source File: ex4_getText2VoiceStream.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getText2VoiceStream(inText,inFileName):

    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)

    message = gigagenieRPC_pb2.reqText()
    message.lang=0
    message.mode=0
    message.text=inText
    writeFile=open(inFileName,'wb')
    for response in stub.getText2VoiceStream(message):
        if response.HasField("resOptions"):
            print ("ResVoiceResult: %d" %(response.resOptions.resultCd))
        if response.HasField("audioContent"):
            print ("Audio Stream")
            writeFile.write(response.audioContent)
    writeFile.close() 
Example #25
Source File: ex2_getVoice2Text.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def getVoice2Text():    

    print ("Ctrl+\ to quit ...")
    
    channel = grpc.secure_channel('{}:{}'.format(HOST, PORT), getCredentials())
    stub = gigagenieRPC_pb2_grpc.GigagenieStub(channel)
    request = generate_request()
    resultText = ''
    for response in stub.getVoice2Text(request):
        if response.resultCd == 200: # partial
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
        elif response.resultCd == 201: # final
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            resultText = response.recognizedText
            break
        else:
            print('resultCd=%d | recognizedText= %s' 
                  % (response.resultCd, response.recognizedText))
            break

    print ("TEXT: %s" % (resultText))
    return resultText 
Example #26
Source File: _load_environment.py    From dm_memorytasks with Apache License 2.0 6 votes vote down vote up
def _create_channel_and_connection(port):
  """Returns a tuple of `(channel, connection)`."""
  for _ in range(_MAX_CONNECTION_ATTEMPTS):
    channel = grpc.secure_channel('localhost:{}'.format(port),
                                  grpc.local_channel_credentials())
    _check_grpc_channel_ready(channel)
    connection = dm_env_rpc_connection.Connection(channel)
    if _can_send_message(connection):
      break
    else:
      # A gRPC server running within Docker sometimes reports that the channel
      # is ready but transitively returns an error (status code 14) on first
      # use.  Giving the server some time to breath and retrying often fixes the
      # problem.
      connection.close()
      channel.close()
      time.sleep(1.0)

  return channel, connection 
Example #27
Source File: service_client.py    From snet-cli with MIT License 6 votes vote down vote up
def _get_grpc_channel(self):
        endpoint = self.options.get("endpoint", None)
        if endpoint is None:
            endpoint = self.service_metadata.get_all_endpoints_for_group(self.group["group_name"])[0]
        endpoint_object = urlparse(endpoint)
        if endpoint_object.port is not None:
            channel_endpoint = endpoint_object.hostname + ":" + str(endpoint_object.port)
        else:
            channel_endpoint = endpoint_object.hostname

        if endpoint_object.scheme == "http":
            return grpc.insecure_channel(channel_endpoint)
        elif endpoint_object.scheme == "https":
            return grpc.secure_channel(channel_endpoint, grpc.ssl_channel_credentials())
        else:
            raise ValueError('Unsupported scheme in service metadata ("{}")'.format(endpoint_object.scheme)) 
Example #28
Source File: lnd_client.py    From node-launcher with MIT License 6 votes vote down vote up
def lnd_client(self):
        if self._lnd_client is not None:
            return self._lnd_client
        auth_credentials = grpc.metadata_call_credentials(
            self.metadata_callback)

        credentials = grpc.composite_channel_credentials(
            self.get_cert_credentials(),
            auth_credentials)

        grpc_channel = grpc.secure_channel(
            f'{self.grpc_host}:{self.grpc_port}',
            credentials,
            options=self.grpc_options
        )
        self._lnd_client = lnrpc.LightningStub(grpc_channel)
        return self._lnd_client 
Example #29
Source File: conftest.py    From gapic-generator-python with Apache License 2.0 6 votes vote down vote up
def intercepted_echo(use_mtls):
    # The interceptor adds 'showcase-trailer' client metadata. Showcase server
    # echos any metadata with key 'showcase-trailer', so the same metadata
    # should appear as trailing metadata in the response.
    interceptor = MetadataClientInterceptor("showcase-trailer", "intercepted")
    host = "localhost:7469"
    channel = (
        grpc.secure_channel(host, ssl_credentials)
        if use_mtls
        else grpc.insecure_channel(host)
    )
    intercept_channel = grpc.intercept_channel(channel, interceptor)
    transport = EchoClient.get_transport_class("grpc")(
        channel=intercept_channel
    )
    return EchoClient(transport=transport) 
Example #30
Source File: channel.py    From aiogrpc with Apache License 2.0 5 votes vote down vote up
def secure_channel(target, credentials, options=None, *, loop=None, executor=None,
                   standalone_pool_for_streaming=False):
    """Creates a secure Channel to a server.

  Args:
    target: The server address.
    credentials: A ChannelCredentials instance.
    options: An optional list of key-value pairs (channel args in gRPC runtime)
    to configure the channel.

  Returns:
    A Channel object.
  """
    return Channel(_grpc.secure_channel(target, credentials, options),
                   loop, executor, standalone_pool_for_streaming)