Debian Codegraph @

examples/python/retry/retry_client.py

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