client.py 2.6 KB

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