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