1# Copyright 2024 The gRPC Authors 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Client of the Python example of token based authentication mechanism.""" 15 16import argparse 17import contextlib 18import logging 19 20import _credentials 21import grpc 22 23helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( 24 "helloworld.proto" 25) 26 27_LOGGER = logging.getLogger(__name__) 28_LOGGER.setLevel(logging.INFO) 29 30_SERVER_ADDR_TEMPLATE = "localhost:%d" 31 32 33@contextlib.contextmanager 34def create_client_channel(addr): 35 # Call credential object will be invoked for every single RPC 36 call_credentials = grpc.access_token_call_credentials( 37 "example_oauth2_token" 38 ) 39 # Channel credential will be valid for the entire channel 40 channel_credential = grpc.ssl_channel_credentials( 41 _credentials.ROOT_CERTIFICATE 42 ) 43 # Combining channel credentials and call credentials together 44 composite_credentials = grpc.composite_channel_credentials( 45 channel_credential, 46 call_credentials, 47 ) 48 channel = grpc.secure_channel(addr, composite_credentials) 49 yield channel 50 51 52def send_rpc(channel): 53 stub = helloworld_pb2_grpc.GreeterStub(channel) 54 request = helloworld_pb2.HelloRequest(name="you") 55 try: 56 response = stub.SayHello(request) 57 except grpc.RpcError as rpc_error: 58 _LOGGER.error("Received error: %s", rpc_error) 59 return rpc_error 60 else: 61 _LOGGER.info("Received message: %s", response) 62 return response 63 64 65def main(): 66 parser = argparse.ArgumentParser() 67 parser.add_argument( 68 "--port", 69 nargs="?", 70 type=int, 71 default=50051, 72 help="the address of server", 73 ) 74 args = parser.parse_args() 75 76 with create_client_channel(_SERVER_ADDR_TEMPLATE % args.port) as channel: 77 send_rpc(channel) 78 79 80if __name__ == "__main__": 81 logging.basicConfig(level=logging.INFO) 82 main() 83