1# Copyright 2023 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"""gRPC Python helloworld.Greeter client with call timeout parameters.""" 15 16import logging 17 18import grpc 19import helloworld_pb2 20import helloworld_pb2_grpc 21 22 23def unary_call( 24 stub: helloworld_pb2_grpc.GreeterStub, request_id: int, message: str 25): 26 print("call:", request_id) 27 try: 28 response = stub.SayHello( 29 helloworld_pb2.HelloRequest(name=message), timeout=3 30 ) 31 print(f"Greeter client received: {response.message}") 32 except grpc.RpcError as rpc_error: 33 print(f"Call failed with code: {rpc_error.code()}") 34 35 36def run(): 37 with grpc.insecure_channel("localhost:50051") as channel: 38 stub = helloworld_pb2_grpc.GreeterStub(channel) 39 # Should success 40 unary_call(stub, 1, "you") 41 # Should fail with DEADLINE_EXCEEDED 42 unary_call(stub, 2, "[delay] you") 43 44 45if __name__ == "__main__": 46 logging.basicConfig() 47 run() 48