server.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 server side with gRPC."""
  15. from __future__ import absolute_import
  16. from __future__ import division
  17. from __future__ import print_function
  18. import argparse
  19. from concurrent import futures
  20. import logging
  21. import threading
  22. import grpc
  23. from examples.protos import helloworld_pb2
  24. from examples.protos import helloworld_pb2_grpc
  25. _DESCRIPTION = 'A server capable of compression.'
  26. _COMPRESSION_OPTIONS = {
  27. "none": grpc.Compression.NoCompression,
  28. "deflate": grpc.Compression.Deflate,
  29. "gzip": grpc.Compression.Gzip,
  30. }
  31. _LOGGER = logging.getLogger(__name__)
  32. _SERVER_HOST = 'localhost'
  33. class Greeter(helloworld_pb2_grpc.GreeterServicer):
  34. def __init__(self, no_compress_every_n):
  35. super(Greeter, self).__init__()
  36. self._no_compress_every_n = 0
  37. self._request_counter = 0
  38. self._counter_lock = threading.RLock()
  39. def _should_suppress_compression(self):
  40. suppress_compression = False
  41. with self._counter_lock:
  42. if self._no_compress_every_n and self._request_counter % self._no_compress_every_n == 0:
  43. suppress_compression = True
  44. self._request_counter += 1
  45. return suppress_compression
  46. def SayHello(self, request, context):
  47. if self._should_suppress_compression():
  48. context.set_response_compression(grpc.Compression.NoCompression)
  49. return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
  50. def run_server(server_compression, no_compress_every_n, port):
  51. server = grpc.server(futures.ThreadPoolExecutor(),
  52. compression=server_compression,
  53. options=(('grpc.so_reuseport', 1),))
  54. helloworld_pb2_grpc.add_GreeterServicer_to_server(
  55. Greeter(no_compress_every_n), server)
  56. address = '{}:{}'.format(_SERVER_HOST, port)
  57. server.add_insecure_port(address)
  58. server.start()
  59. print("Server listening at '{}'".format(address))
  60. server.wait_for_termination()
  61. def main():
  62. parser = argparse.ArgumentParser(description=_DESCRIPTION)
  63. parser.add_argument('--server_compression',
  64. default='none',
  65. nargs='?',
  66. choices=_COMPRESSION_OPTIONS.keys(),
  67. help='The default compression method for the server.')
  68. parser.add_argument('--no_compress_every_n',
  69. type=int,
  70. default=0,
  71. nargs='?',
  72. help='If set, every nth reply will be uncompressed.')
  73. parser.add_argument('--port',
  74. type=int,
  75. default=50051,
  76. nargs='?',
  77. help='The port on which the server will listen.')
  78. args = parser.parse_args()
  79. run_server(_COMPRESSION_OPTIONS[args.server_compression],
  80. args.no_compress_every_n, args.port)
  81. if __name__ == "__main__":
  82. logging.basicConfig()
  83. main()