當前位置: 首頁>>代碼示例>>Python>>正文


Python grpc.ssl_channel_credentials方法代碼示例

本文整理匯總了Python中grpc.ssl_channel_credentials方法的典型用法代碼示例。如果您正苦於以下問題:Python grpc.ssl_channel_credentials方法的具體用法?Python grpc.ssl_channel_credentials怎麽用?Python grpc.ssl_channel_credentials使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在grpc的用法示例。


在下文中一共展示了grpc.ssl_channel_credentials方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
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) 
開發者ID:cea-hpc,項目名稱:pcocc,代碼行數:20,代碼來源:Tbon.py

示例2: run

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
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)) 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:20,代碼來源:bookstore_client.py

示例3: lndDecodeInvoice

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
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 
開發者ID:rootzoll,項目名稱:raspiblitz,代碼行數:26,代碼來源:blitz.ip2tor.py

示例4: lndPayInvoice

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
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 
開發者ID:rootzoll,項目名稱:raspiblitz,代碼行數:27,代碼來源:blitz.ip2tor.py

示例5: main

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
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) 
開發者ID:rootzoll,項目名稱:raspiblitz,代碼行數:22,代碼來源:lnd.initwallet.py

示例6: create_grpc_channel

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
def create_grpc_channel(target, credentials, ssl_credentials_file=None,
                        grpc_channel_options=[]):
    """Create and return a gRPC channel.

    Args:
      credentials(google.oauth2.credentials.Credentials): OAuth2 credentials.
      ssl_credentials_file(str): Path to SSL credentials.pem file
        (for testing).
      grpc_channel_options([(option_name, option_val)]): gRPC channel options.
    Returns:
      grpc.Channel.
    """
    ssl_credentials = None
    if ssl_credentials_file:
        with open(ssl_credentials_file) as f:
            ssl_credentials = grpc.ssl_channel_credentials(f.read())
    http_request = google.auth.transport.requests.Request()
    # TODO(proppy): figure out if/why we need to force a refresh.
    # if yes, consider remove access token from serialized credentials.
    credentials.refresh(http_request)
    return google.auth.transport.grpc.secure_authorized_channel(
        credentials, http_request, target,
        ssl_credentials=ssl_credentials,
        options=grpc_channel_options) 
開發者ID:Deeplocal,項目名稱:mocktailsmixer,代碼行數:26,代碼來源:__init__.py

示例7: get_stub_and_request

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
def get_stub_and_request(endpoint_address, model_name, certs, ssl, target_name, request_type):
    request_type = INFERENCE_REQUEST if request_type is None else request_type
    if ssl:
        server_ca_cert, client_key, client_cert = prepare_certs(server_cert=certs['server_cert'],
                                                                client_key=certs['client_key'],
                                                                client_ca=certs['client_cert'])
        creds = grpc.ssl_channel_credentials(root_certificates=server_ca_cert,
                                             private_key=client_key, certificate_chain=client_cert)
        stub, request = prepare_stub_and_request(address=endpoint_address, model_name=model_name,
                                                 creds=creds, opts=target_name,
                                                 request_type=request_type)
    else:
        stub, request = prepare_stub_and_request(address=endpoint_address, model_name=model_name,
                                                 creds=None, opts=target_name,
                                                 request_type=request_type)
    return stub, request 
開發者ID:IntelAI,項目名稱:inference-model-manager,代碼行數:18,代碼來源:grpc_client.py

示例8: test_prediction_with_certificates

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
def test_prediction_with_certificates():
    time.sleep(30)
    endpoint_info.url = endpoint_info.info
    trusted_cert, trusted_key, trusted_ca = prepare_certs(
        CERT_SERVER,
        CERT_CLIENT_KEY,
        CERT_CLIENT)
    endpoint_info.credentials = grpc.ssl_channel_credentials(root_certificates=trusted_cert,
                                                             private_key=trusted_key,
                                                             certificate_chain=trusted_ca)
    # resnet_v1 test
    prediction_response = perform_inference()
    assert not prediction_response == "Failed"
    response = numpy.array(prediction_response.outputs[model_output].float_val)

    max_output = numpy.argmax(response) - 1
    num_label = classes.imagenet_classes[max_output]
    test_label = classes.imagenet_classes[first_label]
    assert max_output == first_label
    assert num_label == test_label
    assert response.size == 1000 
開發者ID:IntelAI,項目名稱:inference-model-manager,代碼行數:23,代碼來源:test_inference_endpoints.py

示例9: test_wrong_certificates

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [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

示例10: _init_channel

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
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() 
開發者ID:PredixDev,項目名稱:predixpy,代碼行數:19,代碼來源:client.py

示例11: construct_client

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
def construct_client(client_class,
                     use_mtls,
                     transport="grpc",
                     channel_creator=grpc.insecure_channel):
    if use_mtls:
        with mock.patch("grpc.ssl_channel_credentials", autospec=True) as mock_ssl_cred:
            mock_ssl_cred.return_value = ssl_credentials
            client = client_class(
                credentials=credentials.AnonymousCredentials(),
                client_options=client_options,
            )
            mock_ssl_cred.assert_called_once_with(
                certificate_chain=cert, private_key=key
            )
            return client
    else:
        transport = client_class.get_transport_class(transport)(
            channel=channel_creator("localhost:7469")
        )
        return client_class(transport=transport) 
開發者ID:googleapis,項目名稱:gapic-generator-python,代碼行數:22,代碼來源:conftest.py

示例12: __init__

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
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) 
開發者ID:TheThingsNetwork,項目名稱:python-app-sdk,代碼行數:19,代碼來源:application.py

示例13: _get_grpc_channel

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
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)) 
開發者ID:singnet,項目名稱:snet-cli,代碼行數:18,代碼來源:service_client.py

示例14: _get_secure_creds

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
def _get_secure_creds(self, ca_cert, cert_key=None, cert_cert=None):
        cert_key_file = None
        cert_cert_file = None

        with open(ca_cert, 'rb') as f:
            ca_cert_file = f.read()

        if cert_key is not None:
            with open(cert_key, 'rb') as f:
                cert_key_file = f.read()

        if cert_cert is not None:
            with open(cert_cert, 'rb') as f:
                cert_cert_file = f.read()

        return grpc.ssl_channel_credentials(
            ca_cert_file,
            cert_key_file,
            cert_cert_file
        ) 
開發者ID:kragniz,項目名稱:python-etcd3,代碼行數:22,代碼來源:client.py

示例15: create_client

# 需要導入模塊: import grpc [as 別名]
# 或者: from grpc import ssl_channel_credentials [as 別名]
def create_client(addr='localhost:9080'):
    # Read certs
    with open('./tls/ca.crt', 'rb') as f:
        root_ca_cert = f.read()
    with open('./tls/client.user.key', 'rb') as f:
        client_cert_key = f.read()
    with open('./tls/client.user.crt', 'rb') as f:
        client_cert = f.read()

    # Connect to Dgraph via gRPC with mutual TLS.
    creds = grpc.ssl_channel_credentials(root_certificates=root_ca_cert,
                                         private_key=client_cert_key,
                                         certificate_chain=client_cert)
    client_stub = pydgraph.DgraphClientStub(addr, credentials=creds)
    return pydgraph.DgraphClient(client_stub) 
開發者ID:dgraph-io,項目名稱:pydgraph,代碼行數:17,代碼來源:tls_example.py


注:本文中的grpc.ssl_channel_credentials方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。