aboutsummaryrefslogtreecommitdiffhomepage
path: root/examples/python
diff options
context:
space:
mode:
Diffstat (limited to 'examples/python')
-rw-r--r--examples/python/helloworld/greeter_client.py11
-rw-r--r--examples/python/helloworld/greeter_server.py26
-rw-r--r--examples/python/interceptors/default_value/default_value_client_interceptor.py68
-rw-r--r--examples/python/interceptors/default_value/greeter_client.py38
-rw-r--r--examples/python/interceptors/default_value/helloworld_pb2.py134
-rw-r--r--examples/python/interceptors/default_value/helloworld_pb2_grpc.py46
-rw-r--r--examples/python/interceptors/headers/generic_client_interceptor.py55
-rw-r--r--examples/python/interceptors/headers/greeter_client.py36
-rw-r--r--examples/python/interceptors/headers/greeter_server.py52
-rw-r--r--examples/python/interceptors/headers/header_manipulator_client_interceptor.py42
-rw-r--r--examples/python/interceptors/headers/helloworld_pb2.py134
-rw-r--r--examples/python/interceptors/headers/helloworld_pb2_grpc.py46
-rw-r--r--examples/python/interceptors/headers/request_header_validator_interceptor.py39
-rw-r--r--examples/python/multiplex/multiplex_client.py130
-rw-r--r--examples/python/multiplex/multiplex_server.py181
-rw-r--r--examples/python/multiplex/route_guide_resources.py23
-rw-r--r--examples/python/multiplex/run_codegen.py23
-rw-r--r--examples/python/route_guide/route_guide_client.py113
-rw-r--r--examples/python/route_guide/route_guide_resources.py23
-rw-r--r--examples/python/route_guide/route_guide_server.py175
-rw-r--r--examples/python/route_guide/run_codegen.py12
21 files changed, 1039 insertions, 368 deletions
diff --git a/examples/python/helloworld/greeter_client.py b/examples/python/helloworld/greeter_client.py
index d9b2bdfd07..a0aeb47bd7 100644
--- a/examples/python/helloworld/greeter_client.py
+++ b/examples/python/helloworld/greeter_client.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""The Python implementation of the GRPC helloworld.Greeter client."""
from __future__ import print_function
@@ -23,11 +22,11 @@ import helloworld_pb2_grpc
def run():
- channel = grpc.insecure_channel('localhost:50051')
- stub = helloworld_pb2_grpc.GreeterStub(channel)
- response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
- print("Greeter client received: " + response.message)
+ channel = grpc.insecure_channel('localhost:50051')
+ stub = helloworld_pb2_grpc.GreeterStub(channel)
+ response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
+ print("Greeter client received: " + response.message)
if __name__ == '__main__':
- run()
+ run()
diff --git a/examples/python/helloworld/greeter_server.py b/examples/python/helloworld/greeter_server.py
index be61695616..c355662ef8 100644
--- a/examples/python/helloworld/greeter_server.py
+++ b/examples/python/helloworld/greeter_server.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""The Python implementation of the GRPC helloworld.Greeter server."""
from concurrent import futures
@@ -27,20 +26,21 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2_grpc.GreeterServicer):
- def SayHello(self, request, context):
- return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
+ def SayHello(self, request, context):
+ return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
- server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
- helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
- server.add_insecure_port('[::]:50051')
- server.start()
- try:
- while True:
- time.sleep(_ONE_DAY_IN_SECONDS)
- except KeyboardInterrupt:
- server.stop(0)
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
+ helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
+ server.add_insecure_port('[::]:50051')
+ server.start()
+ try:
+ while True:
+ time.sleep(_ONE_DAY_IN_SECONDS)
+ except KeyboardInterrupt:
+ server.stop(0)
+
if __name__ == '__main__':
- serve()
+ serve()
diff --git a/examples/python/interceptors/default_value/default_value_client_interceptor.py b/examples/python/interceptors/default_value/default_value_client_interceptor.py
new file mode 100644
index 0000000000..c549f2b861
--- /dev/null
+++ b/examples/python/interceptors/default_value/default_value_client_interceptor.py
@@ -0,0 +1,68 @@
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Interceptor that adds headers to outgoing requests."""
+
+import collections
+
+import grpc
+
+
+class _ConcreteValue(grpc.Future):
+
+ def __init__(self, result):
+ self._result = result
+
+ def cancel(self):
+ return False
+
+ def cancelled(self):
+ return False
+
+ def running(self):
+ return False
+
+ def done(self):
+ return True
+
+ def result(self, timeout=None):
+ return self._result
+
+ def exception(self, timeout=None):
+ return None
+
+ def traceback(self, timeout=None):
+ return None
+
+ def add_done_callback(self, fn):
+ fn(self._result)
+
+
+class DefaultValueClientInterceptor(grpc.UnaryUnaryClientInterceptor,
+ grpc.StreamUnaryClientInterceptor):
+
+ def __init__(self, value):
+ self._default = _ConcreteValue(value)
+
+ def _intercept_call(self, continuation, client_call_details,
+ request_or_iterator):
+ response = continuation(client_call_details, request_or_iterator)
+ return self._default if response.exception() else response
+
+ def intercept_unary_unary(self, continuation, client_call_details, request):
+ return self._intercept_call(continuation, client_call_details, request)
+
+ def intercept_stream_unary(self, continuation, client_call_details,
+ request_iterator):
+ return self._intercept_call(continuation, client_call_details,
+ request_iterator)
diff --git a/examples/python/interceptors/default_value/greeter_client.py b/examples/python/interceptors/default_value/greeter_client.py
new file mode 100644
index 0000000000..aba7571d83
--- /dev/null
+++ b/examples/python/interceptors/default_value/greeter_client.py
@@ -0,0 +1,38 @@
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The Python implementation of the gRPC helloworld.Greeter client."""
+
+from __future__ import print_function
+
+import grpc
+
+import helloworld_pb2
+import helloworld_pb2_grpc
+import default_value_client_interceptor
+
+
+def run():
+ default_value = helloworld_pb2.HelloReply(
+ message='Hello from your local interceptor!')
+ default_value_interceptor = default_value_client_interceptor.DefaultValueClientInterceptor(
+ default_value)
+ channel = grpc.insecure_channel('localhost:50051')
+ channel = grpc.intercept_channel(channel, default_value_interceptor)
+ stub = helloworld_pb2_grpc.GreeterStub(channel)
+ response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
+ print("Greeter client received: " + response.message)
+
+
+if __name__ == '__main__':
+ run()
diff --git a/examples/python/interceptors/default_value/helloworld_pb2.py b/examples/python/interceptors/default_value/helloworld_pb2.py
new file mode 100644
index 0000000000..e18ab9acc7
--- /dev/null
+++ b/examples/python/interceptors/default_value/helloworld_pb2.py
@@ -0,0 +1,134 @@
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: helloworld.proto
+
+import sys
+_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf import descriptor_pb2
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor.FileDescriptor(
+ name='helloworld.proto',
+ package='helloworld',
+ syntax='proto3',
+ serialized_pb=_b('\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3')
+)
+
+
+
+
+_HELLOREQUEST = _descriptor.Descriptor(
+ name='HelloRequest',
+ full_name='helloworld.HelloRequest',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='name', full_name='helloworld.HelloRequest.name', index=0,
+ number=1, type=9, cpp_type=9, label=1,
+ has_default_value=False, default_value=_b("").decode('utf-8'),
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ syntax='proto3',
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=32,
+ serialized_end=60,
+)
+
+
+_HELLOREPLY = _descriptor.Descriptor(
+ name='HelloReply',
+ full_name='helloworld.HelloReply',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='message', full_name='helloworld.HelloReply.message', index=0,
+ number=1, type=9, cpp_type=9, label=1,
+ has_default_value=False, default_value=_b("").decode('utf-8'),
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ syntax='proto3',
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=62,
+ serialized_end=91,
+)
+
+DESCRIPTOR.message_types_by_name['HelloRequest'] = _HELLOREQUEST
+DESCRIPTOR.message_types_by_name['HelloReply'] = _HELLOREPLY
+_sym_db.RegisterFileDescriptor(DESCRIPTOR)
+
+HelloRequest = _reflection.GeneratedProtocolMessageType('HelloRequest', (_message.Message,), dict(
+ DESCRIPTOR = _HELLOREQUEST,
+ __module__ = 'helloworld_pb2'
+ # @@protoc_insertion_point(class_scope:helloworld.HelloRequest)
+ ))
+_sym_db.RegisterMessage(HelloRequest)
+
+HelloReply = _reflection.GeneratedProtocolMessageType('HelloReply', (_message.Message,), dict(
+ DESCRIPTOR = _HELLOREPLY,
+ __module__ = 'helloworld_pb2'
+ # @@protoc_insertion_point(class_scope:helloworld.HelloReply)
+ ))
+_sym_db.RegisterMessage(HelloReply)
+
+
+DESCRIPTOR.has_options = True
+DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW'))
+
+_GREETER = _descriptor.ServiceDescriptor(
+ name='Greeter',
+ full_name='helloworld.Greeter',
+ file=DESCRIPTOR,
+ index=0,
+ options=None,
+ serialized_start=93,
+ serialized_end=166,
+ methods=[
+ _descriptor.MethodDescriptor(
+ name='SayHello',
+ full_name='helloworld.Greeter.SayHello',
+ index=0,
+ containing_service=None,
+ input_type=_HELLOREQUEST,
+ output_type=_HELLOREPLY,
+ options=None,
+ ),
+])
+_sym_db.RegisterServiceDescriptor(_GREETER)
+
+DESCRIPTOR.services_by_name['Greeter'] = _GREETER
+
+# @@protoc_insertion_point(module_scope)
diff --git a/examples/python/interceptors/default_value/helloworld_pb2_grpc.py b/examples/python/interceptors/default_value/helloworld_pb2_grpc.py
new file mode 100644
index 0000000000..18e07d1679
--- /dev/null
+++ b/examples/python/interceptors/default_value/helloworld_pb2_grpc.py
@@ -0,0 +1,46 @@
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+import grpc
+
+import helloworld_pb2 as helloworld__pb2
+
+
+class GreeterStub(object):
+ """The greeting service definition.
+ """
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.SayHello = channel.unary_unary(
+ '/helloworld.Greeter/SayHello',
+ request_serializer=helloworld__pb2.HelloRequest.SerializeToString,
+ response_deserializer=helloworld__pb2.HelloReply.FromString,
+ )
+
+
+class GreeterServicer(object):
+ """The greeting service definition.
+ """
+
+ def SayHello(self, request, context):
+ """Sends a greeting
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+def add_GreeterServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'SayHello': grpc.unary_unary_rpc_method_handler(
+ servicer.SayHello,
+ request_deserializer=helloworld__pb2.HelloRequest.FromString,
+ response_serializer=helloworld__pb2.HelloReply.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'helloworld.Greeter', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
diff --git a/examples/python/interceptors/headers/generic_client_interceptor.py b/examples/python/interceptors/headers/generic_client_interceptor.py
new file mode 100644
index 0000000000..30b0755aaf
--- /dev/null
+++ b/examples/python/interceptors/headers/generic_client_interceptor.py
@@ -0,0 +1,55 @@
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Base class for interceptors that operate on all RPC types."""
+
+import grpc
+
+
+class _GenericClientInterceptor(
+ grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor,
+ grpc.StreamUnaryClientInterceptor, grpc.StreamStreamClientInterceptor):
+
+ def __init__(self, interceptor_function):
+ self._fn = interceptor_function
+
+ def intercept_unary_unary(self, continuation, client_call_details, request):
+ new_details, new_request_iterator, postprocess = self._fn(
+ client_call_details, iter((request,)), False, False)
+ response = continuation(new_details, next(new_request_iterator))
+ return postprocess(response) if postprocess else response
+
+ def intercept_unary_stream(self, continuation, client_call_details,
+ request):
+ new_details, new_request_iterator, postprocess = self._fn(
+ client_call_details, iter((request,)), False, True)
+ response_it = continuation(new_details, new_request_iterator)
+ return postprocess(response_it) if postprocess else response_it
+
+ def intercept_stream_unary(self, continuation, client_call_details,
+ request_iterator):
+ new_details, new_request_iterator, postprocess = self._fn(
+ client_call_details, request_iterator, True, False)
+ response = continuation(new_details, next(new_request_iterator))
+ return postprocess(response) if postprocess else response
+
+ def intercept_stream_stream(self, continuation, client_call_details,
+ request_iterator):
+ new_details, new_request_iterator, postprocess = self._fn(
+ client_call_details, request_iterator, True, True)
+ response_it = continuation(new_details, new_request_iterator)
+ return postprocess(response_it) if postprocess else response_it
+
+
+def create(intercept_call):
+ return _GenericClientInterceptor(intercept_call)
diff --git a/examples/python/interceptors/headers/greeter_client.py b/examples/python/interceptors/headers/greeter_client.py
new file mode 100644
index 0000000000..2b0dd3e177
--- /dev/null
+++ b/examples/python/interceptors/headers/greeter_client.py
@@ -0,0 +1,36 @@
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The Python implementation of the GRPC helloworld.Greeter client."""
+
+from __future__ import print_function
+
+import grpc
+
+import helloworld_pb2
+import helloworld_pb2_grpc
+import header_manipulator_client_interceptor
+
+
+def run():
+ header_adder_interceptor = header_manipulator_client_interceptor.header_adder_interceptor(
+ 'one-time-password', '42')
+ channel = grpc.insecure_channel('localhost:50051')
+ channel = grpc.intercept_channel(channel, header_adder_interceptor)
+ stub = helloworld_pb2_grpc.GreeterStub(channel)
+ response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
+ print("Greeter client received: " + response.message)
+
+
+if __name__ == '__main__':
+ run()
diff --git a/examples/python/interceptors/headers/greeter_server.py b/examples/python/interceptors/headers/greeter_server.py
new file mode 100644
index 0000000000..01968609b5
--- /dev/null
+++ b/examples/python/interceptors/headers/greeter_server.py
@@ -0,0 +1,52 @@
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""The Python implementation of the GRPC helloworld.Greeter server."""
+
+from concurrent import futures
+import time
+
+import grpc
+
+import helloworld_pb2
+import helloworld_pb2_grpc
+from request_header_validator_interceptor import RequestHeaderValidatorInterceptor
+
+_ONE_DAY_IN_SECONDS = 60 * 60 * 24
+
+
+class Greeter(helloworld_pb2_grpc.GreeterServicer):
+
+ def SayHello(self, request, context):
+ return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
+
+
+def serve():
+ header_validator = RequestHeaderValidatorInterceptor(
+ 'one-time-password', '42', grpc.StatusCode.UNAUTHENTICATED,
+ 'Access denied!')
+ server = grpc.server(
+ futures.ThreadPoolExecutor(max_workers=10),
+ interceptors=(header_validator,))
+ helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
+ server.add_insecure_port('[::]:50051')
+ server.start()
+ try:
+ while True:
+ time.sleep(_ONE_DAY_IN_SECONDS)
+ except KeyboardInterrupt:
+ server.stop(0)
+
+
+if __name__ == '__main__':
+ serve()
diff --git a/examples/python/interceptors/headers/header_manipulator_client_interceptor.py b/examples/python/interceptors/headers/header_manipulator_client_interceptor.py
new file mode 100644
index 0000000000..ac7c605144
--- /dev/null
+++ b/examples/python/interceptors/headers/header_manipulator_client_interceptor.py
@@ -0,0 +1,42 @@
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Interceptor that adds headers to outgoing requests."""
+
+import collections
+
+import grpc
+import generic_client_interceptor
+
+
+class _ClientCallDetails(
+ collections.namedtuple('_ClientCallDetails',
+ ('method', 'timeout', 'metadata',
+ 'credentials')), grpc.ClientCallDetails):
+ pass
+
+
+def header_adder_interceptor(header, value):
+
+ def intercept_call(client_call_details, request_iterator, request_streaming,
+ response_streaming):
+ metadata = []
+ if client_call_details.metadata is not None:
+ metadata = list(client_call_details.metadata)
+ metadata.append((header, value,))
+ client_call_details = _ClientCallDetails(
+ client_call_details.method, client_call_details.timeout, metadata,
+ client_call_details.credentials)
+ return client_call_details, request_iterator, None
+
+ return generic_client_interceptor.create(intercept_call)
diff --git a/examples/python/interceptors/headers/helloworld_pb2.py b/examples/python/interceptors/headers/helloworld_pb2.py
new file mode 100644
index 0000000000..e18ab9acc7
--- /dev/null
+++ b/examples/python/interceptors/headers/helloworld_pb2.py
@@ -0,0 +1,134 @@
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: helloworld.proto
+
+import sys
+_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf import descriptor_pb2
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor.FileDescriptor(
+ name='helloworld.proto',
+ package='helloworld',
+ syntax='proto3',
+ serialized_pb=_b('\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3')
+)
+
+
+
+
+_HELLOREQUEST = _descriptor.Descriptor(
+ name='HelloRequest',
+ full_name='helloworld.HelloRequest',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='name', full_name='helloworld.HelloRequest.name', index=0,
+ number=1, type=9, cpp_type=9, label=1,
+ has_default_value=False, default_value=_b("").decode('utf-8'),
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ syntax='proto3',
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=32,
+ serialized_end=60,
+)
+
+
+_HELLOREPLY = _descriptor.Descriptor(
+ name='HelloReply',
+ full_name='helloworld.HelloReply',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='message', full_name='helloworld.HelloReply.message', index=0,
+ number=1, type=9, cpp_type=9, label=1,
+ has_default_value=False, default_value=_b("").decode('utf-8'),
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ syntax='proto3',
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=62,
+ serialized_end=91,
+)
+
+DESCRIPTOR.message_types_by_name['HelloRequest'] = _HELLOREQUEST
+DESCRIPTOR.message_types_by_name['HelloReply'] = _HELLOREPLY
+_sym_db.RegisterFileDescriptor(DESCRIPTOR)
+
+HelloRequest = _reflection.GeneratedProtocolMessageType('HelloRequest', (_message.Message,), dict(
+ DESCRIPTOR = _HELLOREQUEST,
+ __module__ = 'helloworld_pb2'
+ # @@protoc_insertion_point(class_scope:helloworld.HelloRequest)
+ ))
+_sym_db.RegisterMessage(HelloRequest)
+
+HelloReply = _reflection.GeneratedProtocolMessageType('HelloReply', (_message.Message,), dict(
+ DESCRIPTOR = _HELLOREPLY,
+ __module__ = 'helloworld_pb2'
+ # @@protoc_insertion_point(class_scope:helloworld.HelloReply)
+ ))
+_sym_db.RegisterMessage(HelloReply)
+
+
+DESCRIPTOR.has_options = True
+DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW'))
+
+_GREETER = _descriptor.ServiceDescriptor(
+ name='Greeter',
+ full_name='helloworld.Greeter',
+ file=DESCRIPTOR,
+ index=0,
+ options=None,
+ serialized_start=93,
+ serialized_end=166,
+ methods=[
+ _descriptor.MethodDescriptor(
+ name='SayHello',
+ full_name='helloworld.Greeter.SayHello',
+ index=0,
+ containing_service=None,
+ input_type=_HELLOREQUEST,
+ output_type=_HELLOREPLY,
+ options=None,
+ ),
+])
+_sym_db.RegisterServiceDescriptor(_GREETER)
+
+DESCRIPTOR.services_by_name['Greeter'] = _GREETER
+
+# @@protoc_insertion_point(module_scope)
diff --git a/examples/python/interceptors/headers/helloworld_pb2_grpc.py b/examples/python/interceptors/headers/helloworld_pb2_grpc.py
new file mode 100644
index 0000000000..18e07d1679
--- /dev/null
+++ b/examples/python/interceptors/headers/helloworld_pb2_grpc.py
@@ -0,0 +1,46 @@
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+import grpc
+
+import helloworld_pb2 as helloworld__pb2
+
+
+class GreeterStub(object):
+ """The greeting service definition.
+ """
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.SayHello = channel.unary_unary(
+ '/helloworld.Greeter/SayHello',
+ request_serializer=helloworld__pb2.HelloRequest.SerializeToString,
+ response_deserializer=helloworld__pb2.HelloReply.FromString,
+ )
+
+
+class GreeterServicer(object):
+ """The greeting service definition.
+ """
+
+ def SayHello(self, request, context):
+ """Sends a greeting
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+def add_GreeterServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'SayHello': grpc.unary_unary_rpc_method_handler(
+ servicer.SayHello,
+ request_deserializer=helloworld__pb2.HelloRequest.FromString,
+ response_serializer=helloworld__pb2.HelloReply.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'helloworld.Greeter', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
diff --git a/examples/python/interceptors/headers/request_header_validator_interceptor.py b/examples/python/interceptors/headers/request_header_validator_interceptor.py
new file mode 100644
index 0000000000..95af4177ba
--- /dev/null
+++ b/examples/python/interceptors/headers/request_header_validator_interceptor.py
@@ -0,0 +1,39 @@
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Interceptor that ensures a specific header is present."""
+
+import grpc
+
+
+def _unary_unary_rpc_terminator(code, details):
+
+ def terminate(ignored_request, context):
+ context.abort(code, details)
+
+ return grpc.unary_unary_rpc_method_handler(terminate)
+
+
+class RequestHeaderValidatorInterceptor(grpc.ServerInterceptor):
+
+ def __init__(self, header, value, code, details):
+ self._header = header
+ self._value = value
+ self._terminator = _unary_unary_rpc_terminator(code, details)
+
+ def intercept_service(self, continuation, handler_call_details):
+ if (self._header,
+ self._value) in handler_call_details.invocation_metadata:
+ return continuation(handler_call_details)
+ else:
+ return self._terminator
diff --git a/examples/python/multiplex/multiplex_client.py b/examples/python/multiplex/multiplex_client.py
index c8c700afcd..49713f35b7 100644
--- a/examples/python/multiplex/multiplex_client.py
+++ b/examples/python/multiplex/multiplex_client.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""A client that makes both Greeter and RouteGuide RPCs."""
from __future__ import print_function
@@ -29,98 +28,99 @@ import route_guide_resources
def make_route_note(message, latitude, longitude):
- return route_guide_pb2.RouteNote(
- message=message,
- location=route_guide_pb2.Point(latitude=latitude, longitude=longitude))
+ return route_guide_pb2.RouteNote(
+ message=message,
+ location=route_guide_pb2.Point(latitude=latitude, longitude=longitude))
def guide_get_one_feature(route_guide_stub, point):
- feature = route_guide_stub.GetFeature(point)
- if not feature.location:
- print("Server returned incomplete feature")
- return
+ feature = route_guide_stub.GetFeature(point)
+ if not feature.location:
+ print("Server returned incomplete feature")
+ return
- if feature.name:
- print("Feature called %s at %s" % (feature.name, feature.location))
- else:
- print("Found no feature at %s" % feature.location)
+ if feature.name:
+ print("Feature called %s at %s" % (feature.name, feature.location))
+ else:
+ print("Found no feature at %s" % feature.location)
def guide_get_feature(route_guide_stub):
- guide_get_one_feature(
- route_guide_stub,
- route_guide_pb2.Point(latitude=409146138, longitude=-746188906))
- guide_get_one_feature(
- route_guide_stub, route_guide_pb2.Point(latitude=0, longitude=0))
+ guide_get_one_feature(
+ route_guide_stub,
+ route_guide_pb2.Point(latitude=409146138, longitude=-746188906))
+ guide_get_one_feature(route_guide_stub,
+ route_guide_pb2.Point(latitude=0, longitude=0))
def guide_list_features(route_guide_stub):
- rectangle = route_guide_pb2.Rectangle(
- lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000),
- hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000))
- print("Looking for features between 40, -75 and 42, -73")
+ rectangle = route_guide_pb2.Rectangle(
+ lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000),
+ hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000))
+ print("Looking for features between 40, -75 and 42, -73")
- features = route_guide_stub.ListFeatures(rectangle)
+ features = route_guide_stub.ListFeatures(rectangle)
- for feature in features:
- print("Feature called %s at %s" % (feature.name, feature.location))
+ for feature in features:
+ print("Feature called %s at %s" % (feature.name, feature.location))
def generate_route(feature_list):
- for _ in range(0, 10):
- random_feature = feature_list[random.randint(0, len(feature_list) - 1)]
- print("Visiting point %s" % random_feature.location)
- yield random_feature.location
- time.sleep(random.uniform(0.5, 1.5))
+ for _ in range(0, 10):
+ random_feature = feature_list[random.randint(0, len(feature_list) - 1)]
+ print("Visiting point %s" % random_feature.location)
+ yield random_feature.location
+ time.sleep(random.uniform(0.5, 1.5))
def guide_record_route(route_guide_stub):
- feature_list = route_guide_resources.read_route_guide_database()
+ feature_list = route_guide_resources.read_route_guide_database()
- route_iterator = generate_route(feature_list)
- route_summary = route_guide_stub.RecordRoute(route_iterator)
- print("Finished trip with %s points " % route_summary.point_count)
- print("Passed %s features " % route_summary.feature_count)
- print("Travelled %s meters " % route_summary.distance)
- print("It took %s seconds " % route_summary.elapsed_time)
+ route_iterator = generate_route(feature_list)
+ route_summary = route_guide_stub.RecordRoute(route_iterator)
+ print("Finished trip with %s points " % route_summary.point_count)
+ print("Passed %s features " % route_summary.feature_count)
+ print("Travelled %s meters " % route_summary.distance)
+ print("It took %s seconds " % route_summary.elapsed_time)
def generate_messages():
- messages = [
- make_route_note("First message", 0, 0),
- make_route_note("Second message", 0, 1),
- make_route_note("Third message", 1, 0),
- make_route_note("Fourth message", 0, 0),
- make_route_note("Fifth message", 1, 0),
- ]
- for msg in messages:
- print("Sending %s at %s" % (msg.message, msg.location))
- yield msg
- time.sleep(random.uniform(0.5, 1.0))
+ messages = [
+ make_route_note("First message", 0, 0),
+ make_route_note("Second message", 0, 1),
+ make_route_note("Third message", 1, 0),
+ make_route_note("Fourth message", 0, 0),
+ make_route_note("Fifth message", 1, 0),
+ ]
+ for msg in messages:
+ print("Sending %s at %s" % (msg.message, msg.location))
+ yield msg
+ time.sleep(random.uniform(0.5, 1.0))
def guide_route_chat(route_guide_stub):
- responses = route_guide_stub.RouteChat(generate_messages())
- for response in responses:
- print("Received message %s at %s" % (response.message, response.location))
+ responses = route_guide_stub.RouteChat(generate_messages())
+ for response in responses:
+ print("Received message %s at %s" %
+ (response.message, response.location))
def run():
- channel = grpc.insecure_channel('localhost:50051')
- greeter_stub = helloworld_pb2_grpc.GreeterStub(channel)
- route_guide_stub = route_guide_pb2_grpc.RouteGuideStub(channel)
- greeter_response = greeter_stub.SayHello(
- helloworld_pb2.HelloRequest(name='you'))
- print("Greeter client received: " + greeter_response.message)
- print("-------------- GetFeature --------------")
- guide_get_feature(route_guide_stub)
- print("-------------- ListFeatures --------------")
- guide_list_features(route_guide_stub)
- print("-------------- RecordRoute --------------")
- guide_record_route(route_guide_stub)
- print("-------------- RouteChat --------------")
- guide_route_chat(route_guide_stub)
+ channel = grpc.insecure_channel('localhost:50051')
+ greeter_stub = helloworld_pb2_grpc.GreeterStub(channel)
+ route_guide_stub = route_guide_pb2_grpc.RouteGuideStub(channel)
+ greeter_response = greeter_stub.SayHello(
+ helloworld_pb2.HelloRequest(name='you'))
+ print("Greeter client received: " + greeter_response.message)
+ print("-------------- GetFeature --------------")
+ guide_get_feature(route_guide_stub)
+ print("-------------- ListFeatures --------------")
+ guide_list_features(route_guide_stub)
+ print("-------------- RecordRoute --------------")
+ guide_record_route(route_guide_stub)
+ print("-------------- RouteChat --------------")
+ guide_route_chat(route_guide_stub)
if __name__ == '__main__':
- run()
+ run()
diff --git a/examples/python/multiplex/multiplex_server.py b/examples/python/multiplex/multiplex_server.py
index 9a6e835bed..e2ff671f97 100644
--- a/examples/python/multiplex/multiplex_server.py
+++ b/examples/python/multiplex/multiplex_server.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""A gRPC server servicing both Greeter and RouteGuide RPCs."""
from concurrent import futures
@@ -30,107 +29,111 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24
def _get_feature(feature_db, point):
- """Returns Feature at given location or None."""
- for feature in feature_db:
- if feature.location == point:
- return feature
- return None
+ """Returns Feature at given location or None."""
+ for feature in feature_db:
+ if feature.location == point:
+ return feature
+ return None
def _get_distance(start, end):
- """Distance between two points."""
- coord_factor = 10000000.0
- lat_1 = start.latitude / coord_factor
- lat_2 = end.latitude / coord_factor
- lon_1 = start.longitude / coord_factor
- lon_2 = end.longitude / coord_factor
- lat_rad_1 = math.radians(lat_1)
- lat_rad_2 = math.radians(lat_2)
- delta_lat_rad = math.radians(lat_2 - lat_1)
- delta_lon_rad = math.radians(lon_2 - lon_1)
-
- a = (pow(math.sin(delta_lat_rad / 2), 2) +
- (math.cos(lat_rad_1) * math.cos(lat_rad_2) *
- pow(math.sin(delta_lon_rad / 2), 2)))
- c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
- R = 6371000; # metres
- return R * c;
+ """Distance between two points."""
+ coord_factor = 10000000.0
+ lat_1 = start.latitude / coord_factor
+ lat_2 = end.latitude / coord_factor
+ lon_1 = start.longitude / coord_factor
+ lon_2 = end.longitude / coord_factor
+ lat_rad_1 = math.radians(lat_1)
+ lat_rad_2 = math.radians(lat_2)
+ delta_lat_rad = math.radians(lat_2 - lat_1)
+ delta_lon_rad = math.radians(lon_2 - lon_1)
+
+ a = (pow(math.sin(delta_lat_rad / 2), 2) +
+ (math.cos(lat_rad_1) * math.cos(lat_rad_2) * pow(
+ math.sin(delta_lon_rad / 2), 2)))
+ c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
+ R = 6371000
+ # metres
+ return R * c
class _GreeterServicer(helloworld_pb2_grpc.GreeterServicer):
- def SayHello(self, request, context):
- return helloworld_pb2.HelloReply(message='Hello, {}!'.format(request.name))
+ def SayHello(self, request, context):
+ return helloworld_pb2.HelloReply(
+ message='Hello, {}!'.format(request.name))
class _RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
- """Provides methods that implement functionality of route guide server."""
-
- def __init__(self):
- self.db = route_guide_resources.read_route_guide_database()
-
- def GetFeature(self, request, context):
- feature = _get_feature(self.db, request)
- if feature is None:
- return route_guide_pb2.Feature(name="", location=request)
- else:
- return feature
-
- def ListFeatures(self, request, context):
- left = min(request.lo.longitude, request.hi.longitude)
- right = max(request.lo.longitude, request.hi.longitude)
- top = max(request.lo.latitude, request.hi.latitude)
- bottom = min(request.lo.latitude, request.hi.latitude)
- for feature in self.db:
- if (feature.location.longitude >= left and
- feature.location.longitude <= right and
- feature.location.latitude >= bottom and
- feature.location.latitude <= top):
- yield feature
-
- def RecordRoute(self, request_iterator, context):
- point_count = 0
- feature_count = 0
- distance = 0.0
- prev_point = None
-
- start_time = time.time()
- for point in request_iterator:
- point_count += 1
- if _get_feature(self.db, point):
- feature_count += 1
- if prev_point:
- distance += _get_distance(prev_point, point)
- prev_point = point
-
- elapsed_time = time.time() - start_time
- return route_guide_pb2.RouteSummary(point_count=point_count,
- feature_count=feature_count,
- distance=int(distance),
- elapsed_time=int(elapsed_time))
-
- def RouteChat(self, request_iterator, context):
- prev_notes = []
- for new_note in request_iterator:
- for prev_note in prev_notes:
- if prev_note.location == new_note.location:
- yield prev_note
- prev_notes.append(new_note)
+ """Provides methods that implement functionality of route guide server."""
+
+ def __init__(self):
+ self.db = route_guide_resources.read_route_guide_database()
+
+ def GetFeature(self, request, context):
+ feature = _get_feature(self.db, request)
+ if feature is None:
+ return route_guide_pb2.Feature(name="", location=request)
+ else:
+ return feature
+
+ def ListFeatures(self, request, context):
+ left = min(request.lo.longitude, request.hi.longitude)
+ right = max(request.lo.longitude, request.hi.longitude)
+ top = max(request.lo.latitude, request.hi.latitude)
+ bottom = min(request.lo.latitude, request.hi.latitude)
+ for feature in self.db:
+ if (feature.location.longitude >= left and
+ feature.location.longitude <= right and
+ feature.location.latitude >= bottom and
+ feature.location.latitude <= top):
+ yield feature
+
+ def RecordRoute(self, request_iterator, context):
+ point_count = 0
+ feature_count = 0
+ distance = 0.0
+ prev_point = None
+
+ start_time = time.time()
+ for point in request_iterator:
+ point_count += 1
+ if _get_feature(self.db, point):
+ feature_count += 1
+ if prev_point:
+ distance += _get_distance(prev_point, point)
+ prev_point = point
+
+ elapsed_time = time.time() - start_time
+ return route_guide_pb2.RouteSummary(
+ point_count=point_count,
+ feature_count=feature_count,
+ distance=int(distance),
+ elapsed_time=int(elapsed_time))
+
+ def RouteChat(self, request_iterator, context):
+ prev_notes = []
+ for new_note in request_iterator:
+ for prev_note in prev_notes:
+ if prev_note.location == new_note.location:
+ yield prev_note
+ prev_notes.append(new_note)
def serve():
- server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
- helloworld_pb2_grpc.add_GreeterServicer_to_server(_GreeterServicer(), server)
- route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
- _RouteGuideServicer(), server)
- server.add_insecure_port('[::]:50051')
- server.start()
- try:
- while True:
- time.sleep(_ONE_DAY_IN_SECONDS)
- except KeyboardInterrupt:
- server.stop(0)
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
+ helloworld_pb2_grpc.add_GreeterServicer_to_server(_GreeterServicer(),
+ server)
+ route_guide_pb2_grpc.add_RouteGuideServicer_to_server(_RouteGuideServicer(),
+ server)
+ server.add_insecure_port('[::]:50051')
+ server.start()
+ try:
+ while True:
+ time.sleep(_ONE_DAY_IN_SECONDS)
+ except KeyboardInterrupt:
+ server.stop(0)
if __name__ == '__main__':
- serve()
+ serve()
diff --git a/examples/python/multiplex/route_guide_resources.py b/examples/python/multiplex/route_guide_resources.py
index 0887863660..ace85d6f9d 100644
--- a/examples/python/multiplex/route_guide_resources.py
+++ b/examples/python/multiplex/route_guide_resources.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""Common resources used in the gRPC route guide example."""
import json
@@ -20,19 +19,19 @@ import route_guide_pb2
def read_route_guide_database():
- """Reads the route guide database.
+ """Reads the route guide database.
Returns:
The full contents of the route guide database as a sequence of
route_guide_pb2.Features.
"""
- feature_list = []
- with open("route_guide_db.json") as route_guide_db_file:
- for item in json.load(route_guide_db_file):
- feature = route_guide_pb2.Feature(
- name=item["name"],
- location=route_guide_pb2.Point(
- latitude=item["location"]["latitude"],
- longitude=item["location"]["longitude"]))
- feature_list.append(feature)
- return feature_list
+ feature_list = []
+ with open("route_guide_db.json") as route_guide_db_file:
+ for item in json.load(route_guide_db_file):
+ feature = route_guide_pb2.Feature(
+ name=item["name"],
+ location=route_guide_pb2.Point(
+ latitude=item["location"]["latitude"],
+ longitude=item["location"]["longitude"]))
+ feature_list.append(feature)
+ return feature_list
diff --git a/examples/python/multiplex/run_codegen.py b/examples/python/multiplex/run_codegen.py
index f38d86cf43..d960c3cf16 100644
--- a/examples/python/multiplex/run_codegen.py
+++ b/examples/python/multiplex/run_codegen.py
@@ -11,26 +11,11 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""Generates protocol messages and gRPC stubs."""
from grpc_tools import protoc
-protoc.main(
- (
- '',
- '-I../../protos',
- '--python_out=.',
- '--grpc_python_out=.',
- '../../protos/helloworld.proto',
- )
-)
-protoc.main(
- (
- '',
- '-I../../protos',
- '--python_out=.',
- '--grpc_python_out=.',
- '../../protos/route_guide.proto',
- )
-)
+protoc.main(('', '-I../../protos', '--python_out=.', '--grpc_python_out=.',
+ '../../protos/helloworld.proto',))
+protoc.main(('', '-I../../protos', '--python_out=.', '--grpc_python_out=.',
+ '../../protos/route_guide.proto',))
diff --git a/examples/python/route_guide/route_guide_client.py b/examples/python/route_guide/route_guide_client.py
index a0e32fb6f5..c9d0e96ad6 100644
--- a/examples/python/route_guide/route_guide_client.py
+++ b/examples/python/route_guide/route_guide_client.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""The Python implementation of the gRPC route guide client."""
from __future__ import print_function
@@ -26,89 +25,91 @@ import route_guide_resources
def make_route_note(message, latitude, longitude):
- return route_guide_pb2.RouteNote(
- message=message,
- location=route_guide_pb2.Point(latitude=latitude, longitude=longitude))
+ return route_guide_pb2.RouteNote(
+ message=message,
+ location=route_guide_pb2.Point(latitude=latitude, longitude=longitude))
def guide_get_one_feature(stub, point):
- feature = stub.GetFeature(point)
- if not feature.location:
- print("Server returned incomplete feature")
- return
+ feature = stub.GetFeature(point)
+ if not feature.location:
+ print("Server returned incomplete feature")
+ return
- if feature.name:
- print("Feature called %s at %s" % (feature.name, feature.location))
- else:
- print("Found no feature at %s" % feature.location)
+ if feature.name:
+ print("Feature called %s at %s" % (feature.name, feature.location))
+ else:
+ print("Found no feature at %s" % feature.location)
def guide_get_feature(stub):
- guide_get_one_feature(stub, route_guide_pb2.Point(latitude=409146138, longitude=-746188906))
- guide_get_one_feature(stub, route_guide_pb2.Point(latitude=0, longitude=0))
+ guide_get_one_feature(
+ stub, route_guide_pb2.Point(latitude=409146138, longitude=-746188906))
+ guide_get_one_feature(stub, route_guide_pb2.Point(latitude=0, longitude=0))
def guide_list_features(stub):
- rectangle = route_guide_pb2.Rectangle(
- lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000),
- hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000))
- print("Looking for features between 40, -75 and 42, -73")
+ rectangle = route_guide_pb2.Rectangle(
+ lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000),
+ hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000))
+ print("Looking for features between 40, -75 and 42, -73")
- features = stub.ListFeatures(rectangle)
+ features = stub.ListFeatures(rectangle)
- for feature in features:
- print("Feature called %s at %s" % (feature.name, feature.location))
+ for feature in features:
+ print("Feature called %s at %s" % (feature.name, feature.location))
def generate_route(feature_list):
- for _ in range(0, 10):
- random_feature = feature_list[random.randint(0, len(feature_list) - 1)]
- print("Visiting point %s" % random_feature.location)
- yield random_feature.location
+ for _ in range(0, 10):
+ random_feature = feature_list[random.randint(0, len(feature_list) - 1)]
+ print("Visiting point %s" % random_feature.location)
+ yield random_feature.location
def guide_record_route(stub):
- feature_list = route_guide_resources.read_route_guide_database()
+ feature_list = route_guide_resources.read_route_guide_database()
- route_iterator = generate_route(feature_list)
- route_summary = stub.RecordRoute(route_iterator)
- print("Finished trip with %s points " % route_summary.point_count)
- print("Passed %s features " % route_summary.feature_count)
- print("Travelled %s meters " % route_summary.distance)
- print("It took %s seconds " % route_summary.elapsed_time)
+ route_iterator = generate_route(feature_list)
+ route_summary = stub.RecordRoute(route_iterator)
+ print("Finished trip with %s points " % route_summary.point_count)
+ print("Passed %s features " % route_summary.feature_count)
+ print("Travelled %s meters " % route_summary.distance)
+ print("It took %s seconds " % route_summary.elapsed_time)
def generate_messages():
- messages = [
- make_route_note("First message", 0, 0),
- make_route_note("Second message", 0, 1),
- make_route_note("Third message", 1, 0),
- make_route_note("Fourth message", 0, 0),
- make_route_note("Fifth message", 1, 0),
- ]
- for msg in messages:
- print("Sending %s at %s" % (msg.message, msg.location))
- yield msg
+ messages = [
+ make_route_note("First message", 0, 0),
+ make_route_note("Second message", 0, 1),
+ make_route_note("Third message", 1, 0),
+ make_route_note("Fourth message", 0, 0),
+ make_route_note("Fifth message", 1, 0),
+ ]
+ for msg in messages:
+ print("Sending %s at %s" % (msg.message, msg.location))
+ yield msg
def guide_route_chat(stub):
- responses = stub.RouteChat(generate_messages())
- for response in responses:
- print("Received message %s at %s" % (response.message, response.location))
+ responses = stub.RouteChat(generate_messages())
+ for response in responses:
+ print("Received message %s at %s" %
+ (response.message, response.location))
def run():
- channel = grpc.insecure_channel('localhost:50051')
- stub = route_guide_pb2_grpc.RouteGuideStub(channel)
- print("-------------- GetFeature --------------")
- guide_get_feature(stub)
- print("-------------- ListFeatures --------------")
- guide_list_features(stub)
- print("-------------- RecordRoute --------------")
- guide_record_route(stub)
- print("-------------- RouteChat --------------")
- guide_route_chat(stub)
+ channel = grpc.insecure_channel('localhost:50051')
+ stub = route_guide_pb2_grpc.RouteGuideStub(channel)
+ print("-------------- GetFeature --------------")
+ guide_get_feature(stub)
+ print("-------------- ListFeatures --------------")
+ guide_list_features(stub)
+ print("-------------- RecordRoute --------------")
+ guide_record_route(stub)
+ print("-------------- RouteChat --------------")
+ guide_route_chat(stub)
if __name__ == '__main__':
- run()
+ run()
diff --git a/examples/python/route_guide/route_guide_resources.py b/examples/python/route_guide/route_guide_resources.py
index 0887863660..ace85d6f9d 100644
--- a/examples/python/route_guide/route_guide_resources.py
+++ b/examples/python/route_guide/route_guide_resources.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""Common resources used in the gRPC route guide example."""
import json
@@ -20,19 +19,19 @@ import route_guide_pb2
def read_route_guide_database():
- """Reads the route guide database.
+ """Reads the route guide database.
Returns:
The full contents of the route guide database as a sequence of
route_guide_pb2.Features.
"""
- feature_list = []
- with open("route_guide_db.json") as route_guide_db_file:
- for item in json.load(route_guide_db_file):
- feature = route_guide_pb2.Feature(
- name=item["name"],
- location=route_guide_pb2.Point(
- latitude=item["location"]["latitude"],
- longitude=item["location"]["longitude"]))
- feature_list.append(feature)
- return feature_list
+ feature_list = []
+ with open("route_guide_db.json") as route_guide_db_file:
+ for item in json.load(route_guide_db_file):
+ feature = route_guide_pb2.Feature(
+ name=item["name"],
+ location=route_guide_pb2.Point(
+ latitude=item["location"]["latitude"],
+ longitude=item["location"]["longitude"]))
+ feature_list.append(feature)
+ return feature_list
diff --git a/examples/python/route_guide/route_guide_server.py b/examples/python/route_guide/route_guide_server.py
index a0aa5fdb83..46f3322a39 100644
--- a/examples/python/route_guide/route_guide_server.py
+++ b/examples/python/route_guide/route_guide_server.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""The Python implementation of the gRPC route guide server."""
from concurrent import futures
@@ -28,98 +27,102 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24
def get_feature(feature_db, point):
- """Returns Feature at given location or None."""
- for feature in feature_db:
- if feature.location == point:
- return feature
- return None
+ """Returns Feature at given location or None."""
+ for feature in feature_db:
+ if feature.location == point:
+ return feature
+ return None
def get_distance(start, end):
- """Distance between two points."""
- coord_factor = 10000000.0
- lat_1 = start.latitude / coord_factor
- lat_2 = end.latitude / coord_factor
- lon_1 = start.longitude / coord_factor
- lon_2 = end.longitude / coord_factor
- lat_rad_1 = math.radians(lat_1)
- lat_rad_2 = math.radians(lat_2)
- delta_lat_rad = math.radians(lat_2 - lat_1)
- delta_lon_rad = math.radians(lon_2 - lon_1)
-
- a = (pow(math.sin(delta_lat_rad / 2), 2) +
- (math.cos(lat_rad_1) * math.cos(lat_rad_2) *
- pow(math.sin(delta_lon_rad / 2), 2)))
- c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
- R = 6371000; # metres
- return R * c;
+ """Distance between two points."""
+ coord_factor = 10000000.0
+ lat_1 = start.latitude / coord_factor
+ lat_2 = end.latitude / coord_factor
+ lon_1 = start.longitude / coord_factor
+ lon_2 = end.longitude / coord_factor
+ lat_rad_1 = math.radians(lat_1)
+ lat_rad_2 = math.radians(lat_2)
+ delta_lat_rad = math.radians(lat_2 - lat_1)
+ delta_lon_rad = math.radians(lon_2 - lon_1)
+
+ a = (pow(math.sin(delta_lat_rad / 2), 2) +
+ (math.cos(lat_rad_1) * math.cos(lat_rad_2) * pow(
+ math.sin(delta_lon_rad / 2), 2)))
+ c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
+ R = 6371000
+ # metres
+ return R * c
+
class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
- """Provides methods that implement functionality of route guide server."""
-
- def __init__(self):
- self.db = route_guide_resources.read_route_guide_database()
-
- def GetFeature(self, request, context):
- feature = get_feature(self.db, request)
- if feature is None:
- return route_guide_pb2.Feature(name="", location=request)
- else:
- return feature
-
- def ListFeatures(self, request, context):
- left = min(request.lo.longitude, request.hi.longitude)
- right = max(request.lo.longitude, request.hi.longitude)
- top = max(request.lo.latitude, request.hi.latitude)
- bottom = min(request.lo.latitude, request.hi.latitude)
- for feature in self.db:
- if (feature.location.longitude >= left and
- feature.location.longitude <= right and
- feature.location.latitude >= bottom and
- feature.location.latitude <= top):
- yield feature
-
- def RecordRoute(self, request_iterator, context):
- point_count = 0
- feature_count = 0
- distance = 0.0
- prev_point = None
-
- start_time = time.time()
- for point in request_iterator:
- point_count += 1
- if get_feature(self.db, point):
- feature_count += 1
- if prev_point:
- distance += get_distance(prev_point, point)
- prev_point = point
-
- elapsed_time = time.time() - start_time
- return route_guide_pb2.RouteSummary(point_count=point_count,
- feature_count=feature_count,
- distance=int(distance),
- elapsed_time=int(elapsed_time))
-
- def RouteChat(self, request_iterator, context):
- prev_notes = []
- for new_note in request_iterator:
- for prev_note in prev_notes:
- if prev_note.location == new_note.location:
- yield prev_note
- prev_notes.append(new_note)
+ """Provides methods that implement functionality of route guide server."""
+
+ def __init__(self):
+ self.db = route_guide_resources.read_route_guide_database()
+
+ def GetFeature(self, request, context):
+ feature = get_feature(self.db, request)
+ if feature is None:
+ return route_guide_pb2.Feature(name="", location=request)
+ else:
+ return feature
+
+ def ListFeatures(self, request, context):
+ left = min(request.lo.longitude, request.hi.longitude)
+ right = max(request.lo.longitude, request.hi.longitude)
+ top = max(request.lo.latitude, request.hi.latitude)
+ bottom = min(request.lo.latitude, request.hi.latitude)
+ for feature in self.db:
+ if (feature.location.longitude >= left and
+ feature.location.longitude <= right and
+ feature.location.latitude >= bottom and
+ feature.location.latitude <= top):
+ yield feature
+
+ def RecordRoute(self, request_iterator, context):
+ point_count = 0
+ feature_count = 0
+ distance = 0.0
+ prev_point = None
+
+ start_time = time.time()
+ for point in request_iterator:
+ point_count += 1
+ if get_feature(self.db, point):
+ feature_count += 1
+ if prev_point:
+ distance += get_distance(prev_point, point)
+ prev_point = point
+
+ elapsed_time = time.time() - start_time
+ return route_guide_pb2.RouteSummary(
+ point_count=point_count,
+ feature_count=feature_count,
+ distance=int(distance),
+ elapsed_time=int(elapsed_time))
+
+ def RouteChat(self, request_iterator, context):
+ prev_notes = []
+ for new_note in request_iterator:
+ for prev_note in prev_notes:
+ if prev_note.location == new_note.location:
+ yield prev_note
+ prev_notes.append(new_note)
def serve():
- server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
- route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
- RouteGuideServicer(), server)
- server.add_insecure_port('[::]:50051')
- server.start()
- try:
- while True:
- time.sleep(_ONE_DAY_IN_SECONDS)
- except KeyboardInterrupt:
- server.stop(0)
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
+ route_guide_pb2_grpc.add_RouteGuideServicer_to_server(RouteGuideServicer(),
+ server)
+ server.add_insecure_port('[::]:50051')
+ server.start()
+ try:
+ while True:
+ time.sleep(_ONE_DAY_IN_SECONDS)
+ except KeyboardInterrupt:
+ server.stop(0)
+
if __name__ == '__main__':
- serve()
+ serve()
diff --git a/examples/python/route_guide/run_codegen.py b/examples/python/route_guide/run_codegen.py
index 4b61cf4faa..1ec7fcd51f 100644
--- a/examples/python/route_guide/run_codegen.py
+++ b/examples/python/route_guide/run_codegen.py
@@ -11,17 +11,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
"""Runs protoc with the gRPC plugin to generate messages and gRPC stubs."""
from grpc_tools import protoc
-protoc.main(
- (
- '',
- '-I../../protos',
- '--python_out=.',
- '--grpc_python_out=.',
- '../../protos/route_guide.proto',
- )
-)
+protoc.main(('', '-I../../protos', '--python_out=.', '--grpc_python_out=.',
+ '../../protos/route_guide.proto',))