xref: /aosp_15_r20/external/grpc-grpc/examples/python/compression/client.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1# Copyright 2019 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"""An example of compression on the client side with gRPC."""
15
16from __future__ import absolute_import
17from __future__ import division
18from __future__ import print_function
19
20import argparse
21import logging
22
23import grpc
24import helloworld_pb2
25import helloworld_pb2_grpc
26
27_DESCRIPTION = "A client capable of compression."
28_COMPRESSION_OPTIONS = {
29    "none": grpc.Compression.NoCompression,
30    "deflate": grpc.Compression.Deflate,
31    "gzip": grpc.Compression.Gzip,
32}
33
34_LOGGER = logging.getLogger(__name__)
35_RPC_COUNT = 10
36
37
38def run_client(channel_compression, call_compression, target):
39    with grpc.insecure_channel(
40        target, compression=channel_compression
41    ) as channel:
42        stub = helloworld_pb2_grpc.GreeterStub(channel)
43        for _ in range(_RPC_COUNT):
44            response = stub.SayHello(
45                helloworld_pb2.HelloRequest(name="you"),
46                compression=call_compression,
47                wait_for_ready=True,
48            )
49            print("Response: {}".format(response))
50
51
52def main():
53    parser = argparse.ArgumentParser(description=_DESCRIPTION)
54    parser.add_argument(
55        "--channel_compression",
56        default="none",
57        nargs="?",
58        choices=_COMPRESSION_OPTIONS.keys(),
59        help="The compression method to use for the channel.",
60    )
61    parser.add_argument(
62        "--call_compression",
63        default="none",
64        nargs="?",
65        choices=_COMPRESSION_OPTIONS.keys(),
66        help="The compression method to use for an individual call.",
67    )
68    parser.add_argument(
69        "--server",
70        default="localhost:50051",
71        type=str,
72        nargs="?",
73        help="The host-port pair at which to reach the server.",
74    )
75    args = parser.parse_args()
76    channel_compression = _COMPRESSION_OPTIONS[args.channel_compression]
77    call_compression = _COMPRESSION_OPTIONS[args.call_compression]
78    run_client(channel_compression, call_compression, args.server)
79
80
81if __name__ == "__main__":
82    logging.basicConfig()
83    main()
84