本文整理汇总了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)
示例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))
示例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
示例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
示例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)
示例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)
示例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
示例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
示例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'
示例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()
示例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)
示例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)
示例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))
示例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
)
示例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)