1# Copyright 2021 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"""The Python implementation of the gRPC client-side retry example.""" 15 16import json 17import logging 18 19import grpc 20 21helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( 22 "helloworld.proto" 23) 24 25 26def run(): 27 # The ServiceConfig proto definition can be found: 28 # https://github.com/grpc/grpc-proto/blob/ec886024c2f7b7f597ba89d5b7d60c3f94627b17/grpc/service_config/service_config.proto#L377 29 service_config_json = json.dumps( 30 { 31 "methodConfig": [ 32 { 33 # To apply retry to all methods, put [{}] in the "name" field 34 "name": [ 35 {"service": "helloworld.Greeter", "method": "SayHello"} 36 ], 37 "retryPolicy": { 38 "maxAttempts": 5, 39 "initialBackoff": "0.1s", 40 "maxBackoff": "1s", 41 "backoffMultiplier": 2, 42 "retryableStatusCodes": ["UNAVAILABLE"], 43 }, 44 } 45 ] 46 } 47 ) 48 options = [] 49 # NOTE: the retry feature will be enabled by default >=v1.40.0 50 options.append(("grpc.enable_retries", 1)) 51 options.append(("grpc.service_config", service_config_json)) 52 with grpc.insecure_channel("localhost:50051", options=options) as channel: 53 stub = helloworld_pb2_grpc.GreeterStub(channel) 54 response = stub.SayHello(helloworld_pb2.HelloRequest(name="you")) 55 print("Greeter client received: " + response.message) 56 57 58if __name__ == "__main__": 59 logging.basicConfig() 60 run() 61