Debian Codegraph @

examples/python/compression/server.py

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