Revert examples

pull/21458/head
Richard Belleville 5 years ago
parent c128e61cf4
commit a362c2566d
  1. 2
      .pylintrc-examples
  2. 15
      examples/python/auth/BUILD.bazel
  3. 9
      examples/python/auth/customized_auth_client.py
  4. 13
      examples/python/auth/customized_auth_server.py
  5. 1
      examples/python/auth/test/_auth_example_test.py
  6. 35
      examples/python/cancellation/BUILD.bazel
  7. 11
      examples/python/cancellation/client.py
  8. 18
      examples/python/cancellation/search.py
  9. 11
      examples/python/cancellation/server.py
  10. 12
      examples/python/compression/BUILD.bazel
  11. 8
      examples/python/compression/client.py
  12. 38
      examples/python/compression/helloworld.proto
  13. 11
      examples/python/compression/server.py
  14. 14
      examples/python/data_transmission/BUILD
  15. 5
      examples/python/data_transmission/alts_client.py
  16. 4
      examples/python/data_transmission/alts_server.py
  17. 17
      examples/python/data_transmission/client.py
  18. 174
      examples/python/data_transmission/demo_pb2.py
  19. 106
      examples/python/data_transmission/demo_pb2_grpc.py
  20. 23
      examples/python/data_transmission/server.py
  21. 21
      examples/python/debug/BUILD.bazel
  22. 11
      examples/python/debug/debug_server.py
  23. 38
      examples/python/debug/helloworld.proto
  24. 11
      examples/python/debug/send_message.py
  25. 18
      examples/python/errors/BUILD.bazel
  26. 8
      examples/python/errors/client.py
  27. 38
      examples/python/errors/helloworld.proto
  28. 9
      examples/python/errors/server.py
  29. 7
      examples/python/errors/test/_error_handling_example_test.py
  30. 11
      examples/python/helloworld/greeter_client.py
  31. 8
      examples/python/helloworld/greeter_client_with_options.py
  32. 9
      examples/python/helloworld/greeter_server.py
  33. 11
      examples/python/helloworld/greeter_server_with_reflection.py
  34. 38
      examples/python/helloworld/helloworld.proto
  35. 0
      examples/python/helloworld/helloworld_pb2.py
  36. 0
      examples/python/helloworld/helloworld_pb2_grpc.py
  37. 10
      examples/python/interceptors/default_value/greeter_client.py
  38. 38
      examples/python/interceptors/default_value/helloworld.proto
  39. 134
      examples/python/interceptors/default_value/helloworld_pb2.py
  40. 46
      examples/python/interceptors/default_value/helloworld_pb2_grpc.py
  41. 9
      examples/python/interceptors/headers/greeter_client.py
  42. 10
      examples/python/interceptors/headers/greeter_server.py
  43. 38
      examples/python/interceptors/headers/helloworld.proto
  44. 134
      examples/python/interceptors/headers/helloworld_pb2.py
  45. 46
      examples/python/interceptors/headers/helloworld_pb2_grpc.py
  46. 38
      examples/python/metadata/helloworld.proto
  47. 134
      examples/python/metadata/helloworld_pb2.py
  48. 46
      examples/python/metadata/helloworld_pb2_grpc.py
  49. 7
      examples/python/metadata/metadata_client.py
  50. 9
      examples/python/metadata/metadata_server.py
  51. 38
      examples/python/multiplex/helloworld.proto
  52. 134
      examples/python/multiplex/helloworld_pb2.py
  53. 46
      examples/python/multiplex/helloworld_pb2_grpc.py
  54. 30
      examples/python/multiplex/multiplex_client.py
  55. 29
      examples/python/multiplex/multiplex_server.py
  56. 111
      examples/python/multiplex/route_guide.proto
  57. 331
      examples/python/multiplex/route_guide_pb2.py
  58. 113
      examples/python/multiplex/route_guide_pb2_grpc.py
  59. 13
      examples/python/multiplex/route_guide_resources.py
  60. 31
      examples/python/multiplex/run_codegen.py
  61. 29
      examples/python/multiprocessing/BUILD
  62. 7
      examples/python/multiprocessing/client.py
  63. 9
      examples/python/multiprocessing/server.py
  64. 13
      examples/python/no_codegen/greeter_client.py
  65. 11
      examples/python/no_codegen/greeter_server.py
  66. 2
      examples/python/no_codegen/helloworld.proto
  67. 38
      examples/python/route_guide/helloworld.proto
  68. 111
      examples/python/route_guide/route_guide.proto
  69. 22
      examples/python/route_guide/route_guide_client.py
  70. 331
      examples/python/route_guide/route_guide_pb2.py
  71. 113
      examples/python/route_guide/route_guide_pb2_grpc.py
  72. 12
      examples/python/route_guide/route_guide_resources.py
  73. 19
      examples/python/route_guide/route_guide_server.py
  74. 24
      examples/python/route_guide/run_codegen.py
  75. 7
      examples/python/wait_for_ready/BUILD.bazel
  76. 38
      examples/python/wait_for_ready/helloworld.proto
  77. 13
      examples/python/wait_for_ready/wait_for_ready_example.py
  78. 1
      examples/python/xds/requirements.txt

@ -98,5 +98,3 @@ disable=
no-else-return,
# NOTE(lidiz): Python 3 make object inheritance default, but not PY2
useless-object-inheritance,
# NOTE(rbellevi): Pylint does not recognize grpc.protos() as an import.
wrong-import-position,

@ -33,15 +33,12 @@ py_binary(
name = "customized_auth_client",
testonly = 1,
srcs = ["customized_auth_client.py"],
data = [
"helloworld.proto",
],
imports = ["."],
python_version = "PY3",
deps = [
":_credentials",
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)
@ -49,15 +46,12 @@ py_binary(
name = "customized_auth_server",
testonly = 1,
srcs = ["customized_auth_server.py"],
data = [
"helloworld.proto",
],
imports = ["."],
python_version = "PY3",
deps = [
":_credentials",
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)
@ -69,6 +63,7 @@ py_test(
":_credentials",
":customized_auth_client",
":customized_auth_server",
"//examples:helloworld_py_pb2",
"//src/python/grpcio/grpc:grpcio",
],
)

@ -22,9 +22,8 @@ import contextlib
import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
from examples.python.auth import _credentials
_LOGGER = logging.getLogger(__name__)
@ -73,8 +72,8 @@ def create_client_channel(addr):
def send_rpc(channel):
stub = services.GreeterStub(channel)
request = protos.HelloRequest(name='you')
stub = helloworld_pb2_grpc.GreeterStub(channel)
request = helloworld_pb2.HelloRequest(name='you')
try:
response = stub.SayHello(request)
except grpc.RpcError as rpc_error:

@ -18,14 +18,13 @@ from __future__ import division
from __future__ import print_function
import argparse
from concurrent import futures
import contextlib
import logging
from concurrent import futures
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
from examples.python.auth import _credentials
_LOGGER = logging.getLogger(__name__)
@ -57,10 +56,10 @@ class SignatureValidationInterceptor(grpc.ServerInterceptor):
return self._abortion
class SimpleGreeter(services.GreeterServicer):
class SimpleGreeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, unused_context):
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
@contextlib.contextmanager
@ -68,7 +67,7 @@ def run_server(port):
# Bind interceptor to server
server = grpc.server(futures.ThreadPoolExecutor(),
interceptors=(SignatureValidationInterceptor(),))
services.add_GreeterServicer_to_server(SimpleGreeter(), server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(SimpleGreeter(), server)
# Loading credentials
server_credentials = grpc.ssl_server_credentials(((

@ -20,7 +20,6 @@ from __future__ import print_function
import unittest
import grpc
from examples.python.auth import _credentials
from examples.python.auth import customized_auth_client
from examples.python.auth import customized_auth_server

@ -15,20 +15,36 @@
# limitations under the License.
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load("@rules_proto//proto:defs.bzl", "proto_library")
load("//bazel:python_rules.bzl", "py_grpc_library", "py_proto_library")
package(default_testonly = 1)
proto_library(
name = "hash_name_proto",
srcs = ["hash_name.proto"],
)
py_proto_library(
name = "hash_name_py_pb2",
deps = [":hash_name_proto"],
)
py_grpc_library(
name = "hash_name_py_pb2_grpc",
srcs = [":hash_name_proto"],
deps = [":hash_name_py_pb2"],
)
py_binary(
name = "client",
srcs = ["client.py"],
data = [
"hash_name.proto",
],
python_version = "PY3",
srcs_version = "PY2AND3",
deps = [
":hash_name_py_pb2",
":hash_name_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
"@six",
],
)
@ -36,27 +52,20 @@ py_binary(
py_library(
name = "search",
srcs = ["search.py"],
data = [
"hash_name.proto",
],
srcs_version = "PY2AND3",
deps = [
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
":hash_name_py_pb2",
],
)
py_binary(
name = "server",
srcs = ["server.py"],
data = [
"hash_name.proto",
],
python_version = "PY3",
srcs_version = "PY2AND3",
deps = [
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
":hash_name_py_pb2",
":search",
] + select({
"//conditions:default": ["@futures//:futures"],

@ -24,7 +24,8 @@ import sys
import grpc
protos, services = grpc.protos_and_services("hash_name.proto")
from examples.python.cancellation import hash_name_pb2
from examples.python.cancellation import hash_name_pb2_grpc
_DESCRIPTION = "A client for finding hashes similar to names."
_LOGGER = logging.getLogger(__name__)
@ -32,8 +33,8 @@ _LOGGER = logging.getLogger(__name__)
def run_unary_client(server_target, name, ideal_distance):
with grpc.insecure_channel(server_target) as channel:
stub = services.HashFinderStub(channel)
future = stub.Find.future(protos.HashNameRequest(
stub = hash_name_pb2_grpc.HashFinderStub(channel)
future = stub.Find.future(hash_name_pb2.HashNameRequest(
desired_name=name, ideal_hamming_distance=ideal_distance),
wait_for_ready=True)
@ -49,8 +50,8 @@ def run_unary_client(server_target, name, ideal_distance):
def run_streaming_client(server_target, name, ideal_distance,
interesting_distance):
with grpc.insecure_channel(server_target) as channel:
stub = services.HashFinderStub(channel)
result_generator = stub.FindRange(protos.HashNameRequest(
stub = hash_name_pb2_grpc.HashFinderStub(channel)
result_generator = stub.FindRange(hash_name_pb2.HashNameRequest(
desired_name=name,
ideal_hamming_distance=ideal_distance,
interesting_hamming_distance=interesting_distance),

@ -23,9 +23,7 @@ import itertools
import logging
import struct
import grpc
protos, services = grpc.protos_and_services("hash_name.proto")
from examples.python.cancellation import hash_name_pb2
_LOGGER = logging.getLogger(__name__)
_BYTE_MAX = 255
@ -134,14 +132,16 @@ def search(target,
distance = _get_substring_hamming_distance(candidate_hash, target)
if interesting_hamming_distance is not None and distance <= interesting_hamming_distance:
# Surface interesting candidates, but don't stop.
yield protos.HashNameResponse(secret=base64.b64encode(secret),
hashed_name=candidate_hash,
hamming_distance=distance)
yield hash_name_pb2.HashNameResponse(
secret=base64.b64encode(secret),
hashed_name=candidate_hash,
hamming_distance=distance)
elif distance <= ideal_distance:
# Yield ideal candidate and end the stream.
yield protos.HashNameResponse(secret=base64.b64encode(secret),
hashed_name=candidate_hash,
hamming_distance=distance)
yield hash_name_pb2.HashNameResponse(
secret=base64.b64encode(secret),
hashed_name=candidate_hash,
hamming_distance=distance)
raise StopIteration() # pylint: disable=stop-iteration-return
hashes_computed += 1
if hashes_computed == maximum_hashes:

@ -25,7 +25,8 @@ import threading
import grpc
import search
protos, services = grpc.protos_and_services("hash_name.proto")
from examples.python.cancellation import hash_name_pb2
from examples.python.cancellation import hash_name_pb2_grpc
_LOGGER = logging.getLogger(__name__)
_SERVER_HOST = 'localhost'
@ -33,7 +34,7 @@ _SERVER_HOST = 'localhost'
_DESCRIPTION = "A server for finding hashes similar to names."
class HashFinder(services.HashFinderServicer):
class HashFinder(hash_name_pb2_grpc.HashFinderServicer):
def __init__(self, maximum_hashes):
super(HashFinder, self).__init__()
@ -58,7 +59,7 @@ class HashFinder(services.HashFinderServicer):
context.cancel()
_LOGGER.debug("Servicer thread returning.")
if not candidates:
return protos.HashNameResponse()
return hash_name_pb2.HashNameResponse()
return candidates[-1]
def FindRange(self, request, context):
@ -90,8 +91,8 @@ def _running_server(port, maximum_hashes):
# threads.
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1),
maximum_concurrent_rpcs=1)
services.add_HashFinderServicer_to_server(HashFinder(maximum_hashes),
server)
hash_name_pb2_grpc.add_HashFinderServicer_to_server(
HashFinder(maximum_hashes), server)
address = '{}:{}'.format(_SERVER_HOST, port)
actual_port = server.add_insecure_port(address)
server.start()

@ -15,28 +15,24 @@
py_binary(
name = "server",
srcs = ["server.py"],
data = [
"helloworld.proto",
],
python_version = "PY3",
srcs_version = "PY2AND3",
deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)
py_binary(
name = "client",
srcs = ["client.py"],
data = [
"helloworld.proto",
],
python_version = "PY3",
srcs_version = "PY2AND3",
deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)

@ -19,10 +19,10 @@ from __future__ import print_function
import argparse
import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
_DESCRIPTION = 'A client capable of compression.'
_COMPRESSION_OPTIONS = {
@ -37,8 +37,8 @@ _LOGGER = logging.getLogger(__name__)
def run_client(channel_compression, call_compression, target):
with grpc.insecure_channel(target,
compression=channel_compression) as channel:
stub = services.GreeterStub(channel)
response = stub.SayHello(protos.HelloRequest(name='you'),
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'),
compression=call_compression,
wait_for_ready=True)
print("Response: {}".format(response))

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -21,10 +21,10 @@ from concurrent import futures
import argparse
import logging
import threading
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
_DESCRIPTION = 'A server capable of compression.'
_COMPRESSION_OPTIONS = {
@ -37,7 +37,7 @@ _LOGGER = logging.getLogger(__name__)
_SERVER_HOST = 'localhost'
class Greeter(services.GreeterServicer):
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def __init__(self, no_compress_every_n):
super(Greeter, self).__init__()
@ -56,14 +56,15 @@ class Greeter(services.GreeterServicer):
def SayHello(self, request, context):
if self._should_suppress_compression():
context.set_response_compression(grpc.Compression.NoCompression)
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def run_server(server_compression, no_compress_every_n, port):
server = grpc.server(futures.ThreadPoolExecutor(),
compression=server_compression,
options=(('grpc.so_reuseport', 1),))
services.add_GreeterServicer_to_server(Greeter(no_compress_every_n), server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(
Greeter(no_compress_every_n), server)
address = '{}:{}'.format(_SERVER_HOST, port)
server.add_insecure_port(address)
server.start()

@ -14,21 +14,21 @@
licenses(["notice"]) # 3-clause BSD
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
py_binary(
name = "alts_server",
srcs = [
"alts_server.py",
"demo_pb2.py",
"demo_pb2_grpc.py",
"server.py",
],
data = [
"demo.proto",
],
main = "alts_server.py",
python_version = "PY3",
srcs_version = "PY2AND3",
deps = [
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)
@ -37,15 +37,13 @@ py_binary(
srcs = [
"alts_client.py",
"client.py",
],
data = [
"demo.proto",
"demo_pb2.py",
"demo_pb2_grpc.py",
],
main = "alts_client.py",
python_version = "PY3",
srcs_version = "PY2AND3",
deps = [
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)

@ -17,8 +17,7 @@ The example would only successfully run in GCP environment."""
import grpc
services = grpc.services("demo.proto")
import demo_pb2_grpc
from client import (bidirectional_streaming_method, client_streaming_method,
server_streaming_method, simple_method)
@ -29,7 +28,7 @@ def main():
with grpc.secure_channel(
SERVER_ADDRESS,
credentials=grpc.alts_channel_credentials()) as channel:
stub = services.GRPCDemoStub(channel)
stub = demo_pb2_grpc.GRPCDemoStub(channel)
simple_method(stub)
client_streaming_method(stub)
server_streaming_method(stub)

@ -19,7 +19,7 @@ from concurrent import futures
import grpc
services = grpc.services("demo.proto")
import demo_pb2_grpc
from server import DemoServer
SERVER_ADDRESS = 'localhost:23333'
@ -27,7 +27,7 @@ SERVER_ADDRESS = 'localhost:23333'
def main():
svr = grpc.server(futures.ThreadPoolExecutor())
services.add_GRPCDemoServicer_to_server(DemoServer(), svr)
demo_pb2_grpc.add_GRPCDemoServicer_to_server(DemoServer(), svr)
svr.add_secure_port(SERVER_ADDRESS,
server_credentials=grpc.alts_server_credentials())
print("------------------start Python GRPC server with ALTS encryption")

@ -16,7 +16,8 @@
import time
import grpc
protos, services = grpc.protos_and_services("demo.proto")
import demo_pb2_grpc
import demo_pb2
__all__ = [
'simple_method', 'client_streaming_method', 'server_streaming_method',
@ -36,8 +37,8 @@ CLIENT_ID = 1
# only respond once.)
def simple_method(stub):
print("--------------Call SimpleMethod Begin--------------")
request = protos.Request(client_id=CLIENT_ID,
request_data="called by Python client")
request = demo_pb2.Request(client_id=CLIENT_ID,
request_data="called by Python client")
response = stub.SimpleMethod(request)
print("resp from server(%d), the message=%s" %
(response.server_id, response.response_data))
@ -54,7 +55,7 @@ def client_streaming_method(stub):
# create a generator
def request_messages():
for i in range(5):
request = protos.Request(
request = demo_pb2.Request(
client_id=CLIENT_ID,
request_data=("called by Python client, message:%d" % i))
yield request
@ -70,8 +71,8 @@ def client_streaming_method(stub):
# but the server can return the response many times.)
def server_streaming_method(stub):
print("--------------Call ServerStreamingMethod Begin--------------")
request = protos.Request(client_id=CLIENT_ID,
request_data="called by Python client")
request = demo_pb2.Request(client_id=CLIENT_ID,
request_data="called by Python client")
response_iterator = stub.ServerStreamingMethod(request)
for response in response_iterator:
print("recv from server(%d), message=%s" %
@ -91,7 +92,7 @@ def bidirectional_streaming_method(stub):
# create a generator
def request_messages():
for i in range(5):
request = protos.Request(
request = demo_pb2.Request(
client_id=CLIENT_ID,
request_data=("called by Python client, message: %d" % i))
yield request
@ -107,7 +108,7 @@ def bidirectional_streaming_method(stub):
def main():
with grpc.insecure_channel(SERVER_ADDRESS) as channel:
stub = services.GRPCDemoStub(channel)
stub = demo_pb2_grpc.GRPCDemoStub(channel)
simple_method(stub)

@ -0,0 +1,174 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: demo.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
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='demo.proto',
package='demo',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n\ndemo.proto\x12\x04\x64\x65mo\"2\n\x07Request\x12\x11\n\tclient_id\x18\x01 \x01(\x03\x12\x14\n\x0crequest_data\x18\x02 \x01(\t\"4\n\x08Response\x12\x11\n\tserver_id\x18\x01 \x01(\x03\x12\x15\n\rresponse_data\x18\x02 \x01(\t2\xf0\x01\n\x08GRPCDemo\x12-\n\x0cSimpleMethod\x12\r.demo.Request\x1a\x0e.demo.Response\x12\x38\n\x15\x43lientStreamingMethod\x12\r.demo.Request\x1a\x0e.demo.Response(\x01\x12\x38\n\x15ServerStreamingMethod\x12\r.demo.Request\x1a\x0e.demo.Response0\x01\x12\x41\n\x1c\x42idirectionalStreamingMethod\x12\r.demo.Request\x1a\x0e.demo.Response(\x01\x30\x01\x62\x06proto3')
)
_REQUEST = _descriptor.Descriptor(
name='Request',
full_name='demo.Request',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='client_id', full_name='demo.Request.client_id', index=0,
number=1, type=3, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='request_data', full_name='demo.Request.request_data', index=1,
number=2, 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,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=20,
serialized_end=70,
)
_RESPONSE = _descriptor.Descriptor(
name='Response',
full_name='demo.Response',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='server_id', full_name='demo.Response.server_id', index=0,
number=1, type=3, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='response_data', full_name='demo.Response.response_data', index=1,
number=2, 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,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=72,
serialized_end=124,
)
DESCRIPTOR.message_types_by_name['Request'] = _REQUEST
DESCRIPTOR.message_types_by_name['Response'] = _RESPONSE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Request = _reflection.GeneratedProtocolMessageType('Request', (_message.Message,), {
'DESCRIPTOR' : _REQUEST,
'__module__' : 'demo_pb2'
# @@protoc_insertion_point(class_scope:demo.Request)
})
_sym_db.RegisterMessage(Request)
Response = _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), {
'DESCRIPTOR' : _RESPONSE,
'__module__' : 'demo_pb2'
# @@protoc_insertion_point(class_scope:demo.Response)
})
_sym_db.RegisterMessage(Response)
_GRPCDEMO = _descriptor.ServiceDescriptor(
name='GRPCDemo',
full_name='demo.GRPCDemo',
file=DESCRIPTOR,
index=0,
serialized_options=None,
serialized_start=127,
serialized_end=367,
methods=[
_descriptor.MethodDescriptor(
name='SimpleMethod',
full_name='demo.GRPCDemo.SimpleMethod',
index=0,
containing_service=None,
input_type=_REQUEST,
output_type=_RESPONSE,
serialized_options=None,
),
_descriptor.MethodDescriptor(
name='ClientStreamingMethod',
full_name='demo.GRPCDemo.ClientStreamingMethod',
index=1,
containing_service=None,
input_type=_REQUEST,
output_type=_RESPONSE,
serialized_options=None,
),
_descriptor.MethodDescriptor(
name='ServerStreamingMethod',
full_name='demo.GRPCDemo.ServerStreamingMethod',
index=2,
containing_service=None,
input_type=_REQUEST,
output_type=_RESPONSE,
serialized_options=None,
),
_descriptor.MethodDescriptor(
name='BidirectionalStreamingMethod',
full_name='demo.GRPCDemo.BidirectionalStreamingMethod',
index=3,
containing_service=None,
input_type=_REQUEST,
output_type=_RESPONSE,
serialized_options=None,
),
])
_sym_db.RegisterServiceDescriptor(_GRPCDEMO)
DESCRIPTOR.services_by_name['GRPCDemo'] = _GRPCDEMO
# @@protoc_insertion_point(module_scope)

@ -0,0 +1,106 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import demo_pb2 as demo__pb2
class GRPCDemoStub(object):
"""service是用来给GRPC服务定义方法的, 格式固定, 类似于Golang中定义一个接口
`service` is used to define methods for GRPC services in a fixed format, similar to defining an interface in Golang
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.SimpleMethod = channel.unary_unary(
'/demo.GRPCDemo/SimpleMethod',
request_serializer=demo__pb2.Request.SerializeToString,
response_deserializer=demo__pb2.Response.FromString,
)
self.ClientStreamingMethod = channel.stream_unary(
'/demo.GRPCDemo/ClientStreamingMethod',
request_serializer=demo__pb2.Request.SerializeToString,
response_deserializer=demo__pb2.Response.FromString,
)
self.ServerStreamingMethod = channel.unary_stream(
'/demo.GRPCDemo/ServerStreamingMethod',
request_serializer=demo__pb2.Request.SerializeToString,
response_deserializer=demo__pb2.Response.FromString,
)
self.BidirectionalStreamingMethod = channel.stream_stream(
'/demo.GRPCDemo/BidirectionalStreamingMethod',
request_serializer=demo__pb2.Request.SerializeToString,
response_deserializer=demo__pb2.Response.FromString,
)
class GRPCDemoServicer(object):
"""service是用来给GRPC服务定义方法的, 格式固定, 类似于Golang中定义一个接口
`service` is used to define methods for GRPC services in a fixed format, similar to defining an interface in Golang
"""
def SimpleMethod(self, request, context):
"""简单模式
unary-unary
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ClientStreamingMethod(self, request_iterator, context):
"""客户端流模式(在一次调用中, 客户端可以多次向服务器传输数据, 但是服务器只能返回一次响应)
stream-unary (In a single call, the client can transfer data to the server several times,
but the server can only return a response once.)
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ServerStreamingMethod(self, request, context):
"""服务端流模式(在一次调用中, 客户端只能一次向服务器传输数据, 但是服务器可以多次返回响应)
unary-stream (In a single call, the client can only transmit data to the server at one time,
but the server can return the response many times.)
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def BidirectionalStreamingMethod(self, request_iterator, context):
"""双向流模式 (在一次调用中, 客户端和服务器都可以向对方多次收发数据)
stream-stream (In a single call, both client and server can send and receive data
to each other multiple times.)
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_GRPCDemoServicer_to_server(servicer, server):
rpc_method_handlers = {
'SimpleMethod': grpc.unary_unary_rpc_method_handler(
servicer.SimpleMethod,
request_deserializer=demo__pb2.Request.FromString,
response_serializer=demo__pb2.Response.SerializeToString,
),
'ClientStreamingMethod': grpc.stream_unary_rpc_method_handler(
servicer.ClientStreamingMethod,
request_deserializer=demo__pb2.Request.FromString,
response_serializer=demo__pb2.Response.SerializeToString,
),
'ServerStreamingMethod': grpc.unary_stream_rpc_method_handler(
servicer.ServerStreamingMethod,
request_deserializer=demo__pb2.Request.FromString,
response_serializer=demo__pb2.Response.SerializeToString,
),
'BidirectionalStreamingMethod': grpc.stream_stream_rpc_method_handler(
servicer.BidirectionalStreamingMethod,
request_deserializer=demo__pb2.Request.FromString,
response_serializer=demo__pb2.Response.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'demo.GRPCDemo', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))

@ -17,15 +17,15 @@ from threading import Thread
from concurrent import futures
import grpc
protos, services = grpc.protos_and_services("demo.proto")
import demo_pb2_grpc
import demo_pb2
__all__ = 'DemoServer'
SERVER_ADDRESS = 'localhost:23333'
SERVER_ID = 1
class DemoServer(services.GRPCDemoServicer):
class DemoServer(demo_pb2_grpc.GRPCDemoServicer):
# 一元模式(在一次调用中, 客户端只能向服务器传输一次请求数据, 服务器也只能返回一次响应)
# unary-unary(In a single call, the client can only send request once, and the server can
@ -33,7 +33,7 @@ class DemoServer(services.GRPCDemoServicer):
def SimpleMethod(self, request, context):
print("SimpleMethod called by client(%d) the message: %s" %
(request.client_id, request.request_data))
response = protos.Response(
response = demo_pb2.Response(
server_id=SERVER_ID,
response_data="Python server SimpleMethod Ok!!!!")
return response
@ -46,7 +46,7 @@ class DemoServer(services.GRPCDemoServicer):
for request in request_iterator:
print("recv from client(%d), message= %s" %
(request.client_id, request.request_data))
response = protos.Response(
response = demo_pb2.Response(
server_id=SERVER_ID,
response_data="Python server ClientStreamingMethod ok")
return response
@ -62,7 +62,7 @@ class DemoServer(services.GRPCDemoServicer):
# create a generator
def response_messages():
for i in range(5):
response = protos.Response(
response = demo_pb2.Response(
server_id=SERVER_ID,
response_data=("send by Python server, message=%d" % i))
yield response
@ -86,7 +86,7 @@ class DemoServer(services.GRPCDemoServicer):
t.start()
for i in range(5):
yield protos.Response(
yield demo_pb2.Response(
server_id=SERVER_ID,
response_data=("send by Python server, message= %d" % i))
@ -96,13 +96,20 @@ class DemoServer(services.GRPCDemoServicer):
def main():
server = grpc.server(futures.ThreadPoolExecutor())
services.add_GRPCDemoServicer_to_server(DemoServer(), server)
demo_pb2_grpc.add_GRPCDemoServicer_to_server(DemoServer(), server)
server.add_insecure_port(SERVER_ADDRESS)
print("------------------start Python GRPC server")
server.start()
server.wait_for_termination()
# If raise Error:
# AttributeError: '_Server' object has no attribute 'wait_for_termination'
# You can use the following code instead:
# import time
# while 1:
# time.sleep(10)
if __name__ == '__main__':
main()

@ -18,14 +18,11 @@ py_binary(
name = "debug_server",
testonly = 1,
srcs = ["debug_server.py"],
data = [
"helloworld.proto",
],
imports = ["."],
deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//src/python/grpcio_channelz/grpc_channelz/v1:grpc_channelz",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)
@ -33,14 +30,11 @@ py_binary(
name = "send_message",
testonly = 1,
srcs = ["send_message.py"],
data = [
"helloworld.proto",
],
imports = ["."],
python_version = "PY3",
deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)
@ -48,7 +42,6 @@ py_binary(
name = "get_stats",
testonly = 1,
srcs = ["get_stats.py"],
imports = ["."],
python_version = "PY3",
deps = [
"//src/python/grpcio/grpc:grpcio",
@ -59,16 +52,14 @@ py_binary(
py_test(
name = "_debug_example_test",
srcs = ["test/_debug_example_test.py"],
data = [
"helloworld.proto",
],
python_version = "PY3",
deps = [
":debug_server",
":get_stats",
":send_message",
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//src/python/grpcio_channelz/grpc_channelz/v1:grpc_channelz",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)

@ -25,7 +25,8 @@ import random
import grpc
from grpc_channelz.v1 import channelz
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.INFO)
@ -33,7 +34,7 @@ _LOGGER.setLevel(logging.INFO)
_RANDOM_FAILURE_RATE = 0.3
class FaultInjectGreeter(services.GreeterServicer):
class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer):
def __init__(self, failure_rate):
self._failure_rate = failure_rate
@ -42,13 +43,13 @@ class FaultInjectGreeter(services.GreeterServicer):
if random.random() < self._failure_rate:
context.abort(grpc.StatusCode.UNAVAILABLE,
'Randomly injected failure.')
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def create_server(addr, failure_rate):
server = grpc.server(futures.ThreadPoolExecutor())
services.add_GreeterServicer_to_server(FaultInjectGreeter(failure_rate),
server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(
FaultInjectGreeter(failure_rate), server)
# Add Channelz Servicer to the gRPC server
channelz.add_channelz_servicer(server)

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -17,12 +17,11 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import logging
import argparse
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
def process(stub, request):
@ -36,8 +35,8 @@ def process(stub, request):
def run(addr, n):
with grpc.insecure_channel(addr) as channel:
stub = services.GreeterStub(channel)
request = protos.HelloRequest(name='you')
stub = helloworld_pb2_grpc.GreeterStub(channel)
request = helloworld_pb2.HelloRequest(name='you')
for _ in range(n):
process(stub, request)

@ -18,14 +18,11 @@ py_library(
name = "client",
testonly = 1,
srcs = ["client.py"],
data = [
"helloworld.proto",
],
imports = ["."],
deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//src/python/grpcio_status/grpc_status",
"//tools/distrib/python/grpcio_tools:grpc_tools",
requirement("googleapis-common-protos"),
],
)
@ -34,14 +31,11 @@ py_library(
name = "server",
testonly = 1,
srcs = ["server.py"],
data = [
"helloworld.proto",
],
imports = ["."],
deps = [
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
"//src/python/grpcio_status/grpc_status:grpc_status",
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
] + select({
"//conditions:default": [requirement("futures")],
"//:python3": [],
@ -52,9 +46,6 @@ py_test(
name = "test/_error_handling_example_test",
size = "small",
srcs = ["test/_error_handling_example_test.py"],
data = [
"helloworld.proto",
],
imports = [
"../../../src/python/grpcio_status",
"../../../src/python/grpcio_tests",
@ -64,6 +55,5 @@ py_test(
":client",
":server",
"//src/python/grpcio_tests/tests:bazel_namespace_package_hack",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)

@ -14,21 +14,21 @@
"""This example handles rich error status in client-side."""
from __future__ import print_function
import logging
import grpc
from grpc_status import rpc_status
from google.rpc import error_details_pb2
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
_LOGGER = logging.getLogger(__name__)
def process(stub):
try:
response = stub.SayHello(protos.HelloRequest(name='Alice'))
response = stub.SayHello(helloworld_pb2.HelloRequest(name='Alice'))
_LOGGER.info('Call success: %s', response.message)
except grpc.RpcError as rpc_error:
_LOGGER.error('Call failure: %s', rpc_error)
@ -47,7 +47,7 @@ def main():
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
stub = services.GreeterStub(channel)
stub = helloworld_pb2_grpc.GreeterStub(channel)
process(stub)

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -23,7 +23,8 @@ from grpc_status import rpc_status
from google.protobuf import any_pb2
from google.rpc import code_pb2, status_pb2, error_details_pb2
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
def create_greet_limit_exceed_error_status(name):
@ -42,7 +43,7 @@ def create_greet_limit_exceed_error_status(name):
)
class LimitedGreeter(services.GreeterServicer):
class LimitedGreeter(helloworld_pb2_grpc.GreeterServicer):
def __init__(self):
self._lock = threading.RLock()
@ -56,12 +57,12 @@ class LimitedGreeter(services.GreeterServicer):
context.abort_with_status(rpc_status.to_status(rich_status))
else:
self._greeted.add(request.name)
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def create_server(server_address):
server = grpc.server(futures.ThreadPoolExecutor())
services.add_GreeterServicer_to_server(LimitedGreeter(), server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(LimitedGreeter(), server)
port = server.add_insecure_port(server_address)
return server, port

@ -21,13 +21,12 @@ try:
except ImportError:
pass
import logging
import unittest
import logging
import grpc
services = grpc.services("helloworld.proto")
from examples import helloworld_pb2_grpc
from examples.python.errors import client as error_handling_client
from examples.python.errors import server as error_handling_server
@ -44,7 +43,7 @@ class ErrorHandlingExampleTest(unittest.TestCase):
self._server.stop(None)
def test_error_handling_example(self):
stub = services.GreeterStub(self._channel)
stub = helloworld_pb2_grpc.GreeterStub(self._channel)
error_handling_client.process(stub)
error_handling_client.process(stub)
# No unhandled exception raised, test passed!

@ -18,11 +18,8 @@ import logging
import grpc
# NOTE: The path to the .proto file must be reachable from an entry
# on sys.path. Use sys.path.insert or set the $PYTHONPATH variable to
# import from files located elsewhere on the filesystem.
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
def run():
@ -30,8 +27,8 @@ def run():
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
stub = services.GreeterStub(channel)
response = stub.SayHello(protos.HelloRequest(name='you'))
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)

@ -18,7 +18,8 @@ import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
def run():
@ -32,10 +33,11 @@ def run():
('grpc.enable_retries', 0),
('grpc.keepalive_timeout_ms', 10000)
]) as channel:
stub = services.GreeterStub(channel)
stub = helloworld_pb2_grpc.GreeterStub(channel)
# Timeout in seconds.
# Please refer gRPC Python documents for more detail. https://grpc.io/grpc/python/grpc.html
response = stub.SayHello(protos.HelloRequest(name='you'), timeout=10)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'),
timeout=10)
print("Greeter client received: " + response.message)

@ -18,18 +18,19 @@ import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(services.GreeterServicer):
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
services.add_GreeterServicer_to_server(Greeter(), server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()

@ -19,20 +19,21 @@ import logging
import grpc
from grpc_reflection.v1alpha import reflection
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(services.GreeterServicer):
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
services.add_GreeterServicer_to_server(Greeter(), server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
SERVICE_NAMES = (
protos.DESCRIPTOR.services_by_name['Greeter'].full_name,
helloworld_pb2.DESCRIPTOR.services_by_name['Greeter'].full_name,
reflection.SERVICE_NAME,
)
reflection.enable_server_reflection(SERVICE_NAMES, server)

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -18,13 +18,13 @@ import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
import default_value_client_interceptor
def run():
default_value = protos.HelloReply(
default_value = helloworld_pb2.HelloReply(
message='Hello from your local interceptor!')
default_value_interceptor = default_value_client_interceptor.DefaultValueClientInterceptor(
default_value)
@ -34,8 +34,8 @@ def run():
with grpc.insecure_channel('localhost:50051') as channel:
intercept_channel = grpc.intercept_channel(channel,
default_value_interceptor)
stub = services.GreeterStub(intercept_channel)
response = stub.SayHello(protos.HelloRequest(name='you'))
stub = helloworld_pb2_grpc.GreeterStub(intercept_channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -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)

@ -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,))

@ -14,13 +14,12 @@
"""The Python implementation of the GRPC helloworld.Greeter client."""
from __future__ import print_function
import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
import header_manipulator_client_interceptor
@ -33,8 +32,8 @@ def run():
with grpc.insecure_channel('localhost:50051') as channel:
intercept_channel = grpc.intercept_channel(channel,
header_adder_interceptor)
stub = services.GreeterStub(intercept_channel)
response = stub.SayHello(protos.HelloRequest(name='you'))
stub = helloworld_pb2_grpc.GreeterStub(intercept_channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)

@ -18,15 +18,15 @@ import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
from request_header_validator_interceptor import RequestHeaderValidatorInterceptor
class Greeter(services.GreeterServicer):
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
@ -35,7 +35,7 @@ def serve():
'Access denied!')
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),
interceptors=(header_validator,))
services.add_GreeterServicer_to_server(Greeter(), server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -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)

@ -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,))

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -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)

@ -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,))

@ -18,7 +18,8 @@ import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
def run():
@ -26,9 +27,9 @@ def run():
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
stub = services.GreeterStub(channel)
stub = helloworld_pb2_grpc.GreeterStub(channel)
response, call = stub.SayHello.with_call(
protos.HelloRequest(name='you'),
helloworld_pb2.HelloRequest(name='you'),
metadata=(
('initial-metadata-1', 'The value should be str'),
('binary-metadata-bin',

@ -19,10 +19,11 @@ import logging
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(services.GreeterServicer):
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
for key, value in context.invocation_metadata():
@ -32,12 +33,12 @@ class Greeter(services.GreeterServicer):
('checksum-bin', b'I agree'),
('retry', 'false'),
))
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
services.add_GreeterServicer_to_server(Greeter(), server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -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)

@ -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,))

@ -21,16 +21,17 @@ import logging
import grpc
hw_protos, hw_services = grpc.protos_and_services("helloworld.proto")
rg_protos, rg_services = grpc.protos_and_services("route_guide.proto")
import helloworld_pb2
import helloworld_pb2_grpc
import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources
def make_route_note(message, latitude, longitude):
return rg_protos.RouteNote(message=message,
location=rg_protos.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):
@ -48,16 +49,15 @@ def guide_get_one_feature(route_guide_stub, point):
def guide_get_feature(route_guide_stub):
guide_get_one_feature(
route_guide_stub,
rg_protos.Point(latitude=409146138, longitude=-746188906))
route_guide_pb2.Point(latitude=409146138, longitude=-746188906))
guide_get_one_feature(route_guide_stub,
rg_protos.Point(latitude=0, longitude=0))
route_guide_pb2.Point(latitude=0, longitude=0))
def guide_list_features(route_guide_stub):
rectangle = rg_protos.Rectangle(lo=rg_protos.Point(latitude=400000000,
longitude=-750000000),
hi=rg_protos.Point(latitude=420000000,
longitude=-730000000))
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)
@ -111,10 +111,10 @@ def run():
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
greeter_stub = hw_services.GreeterStub(channel)
route_guide_stub = rg_services.RouteGuideStub(channel)
greeter_stub = helloworld_pb2_grpc.GreeterStub(channel)
route_guide_stub = route_guide_pb2_grpc.RouteGuideStub(channel)
greeter_response = greeter_stub.SayHello(
hw_protos.HelloRequest(name='you'))
helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + greeter_response.message)
print("-------------- GetFeature --------------")
guide_get_feature(route_guide_stub)

@ -20,8 +20,10 @@ import logging
import grpc
hw_protos, hw_services = grpc.protos_and_services("helloworld.proto")
rg_protos, rg_services = grpc.protos_and_services("route_guide.proto")
import helloworld_pb2
import helloworld_pb2_grpc
import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources
@ -54,13 +56,14 @@ def _get_distance(start, end):
return R * c
class _GreeterServicer(hw_services.GreeterServicer):
class _GreeterServicer(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return hw_protos.HelloReply(message='Hello, {}!'.format(request.name))
return helloworld_pb2.HelloReply(
message='Hello, {}!'.format(request.name))
class _RouteGuideServicer(rg_services.RouteGuideServicer):
class _RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
"""Provides methods that implement functionality of route guide server."""
def __init__(self):
@ -69,7 +72,7 @@ class _RouteGuideServicer(rg_services.RouteGuideServicer):
def GetFeature(self, request, context):
feature = _get_feature(self.db, request)
if feature is None:
return rg_protos.Feature(name="", location=request)
return route_guide_pb2.Feature(name="", location=request)
else:
return feature
@ -101,10 +104,10 @@ class _RouteGuideServicer(rg_services.RouteGuideServicer):
prev_point = point
elapsed_time = time.time() - start_time
return rg_protos.RouteSummary(point_count=point_count,
feature_count=feature_count,
distance=int(distance),
elapsed_time=int(elapsed_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 = []
@ -117,8 +120,10 @@ class _RouteGuideServicer(rg_services.RouteGuideServicer):
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
hw_services.add_GreeterServicer_to_server(_GreeterServicer(), server)
rg_services.add_RouteGuideServicer_to_server(_RouteGuideServicer(), server)
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()
server.wait_for_termination()

@ -1,111 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.routeguide";
option java_outer_classname = "RouteGuideProto";
option objc_class_prefix = "RTG";
package routeguide;
// Interface exported by the server.
service RouteGuide {
// A simple RPC.
//
// Obtains the feature at a given position.
//
// A feature with an empty name is returned if there's no feature at the given
// position.
rpc GetFeature(Point) returns (Feature) {}
// A server-to-client streaming RPC.
//
// Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
// huge number of features.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
// A client-to-server streaming RPC.
//
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
// A Bidirectional streaming RPC.
//
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
}
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
// A latitude-longitude rectangle, represented as two diagonally opposite
// points "lo" and "hi".
message Rectangle {
// One corner of the rectangle.
Point lo = 1;
// The other corner of the rectangle.
Point hi = 2;
}
// A feature names something at a given point.
//
// If a feature could not be named, the name is empty.
message Feature {
// The name of the feature.
string name = 1;
// The point where the feature is detected.
Point location = 2;
}
// A RouteNote is a message sent while at a given point.
message RouteNote {
// The location from which the message is sent.
Point location = 1;
// The message to be sent.
string message = 2;
}
// A RouteSummary is received in response to a RecordRoute rpc.
//
// It contains the number of individual points received, the number of
// detected features, and the total distance covered as the cumulative sum of
// the distance between each point.
message RouteSummary {
// The number of points received.
int32 point_count = 1;
// The number of known features passed while traversing the route.
int32 feature_count = 2;
// The distance covered in metres.
int32 distance = 3;
// The duration of the traversal in seconds.
int32 elapsed_time = 4;
}

@ -0,0 +1,331 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: route_guide.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='route_guide.proto',
package='routeguide',
syntax='proto3',
serialized_pb=_b('\n\x11route_guide.proto\x12\nrouteguide\",\n\x05Point\x12\x10\n\x08latitude\x18\x01 \x01(\x05\x12\x11\n\tlongitude\x18\x02 \x01(\x05\"I\n\tRectangle\x12\x1d\n\x02lo\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x1d\n\x02hi\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"<\n\x07\x46\x65\x61ture\x12\x0c\n\x04name\x18\x01 \x01(\t\x12#\n\x08location\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"A\n\tRouteNote\x12#\n\x08location\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x0f\n\x07message\x18\x02 \x01(\t\"b\n\x0cRouteSummary\x12\x13\n\x0bpoint_count\x18\x01 \x01(\x05\x12\x15\n\rfeature_count\x18\x02 \x01(\x05\x12\x10\n\x08\x64istance\x18\x03 \x01(\x05\x12\x14\n\x0c\x65lapsed_time\x18\x04 \x01(\x05\x32\x85\x02\n\nRouteGuide\x12\x36\n\nGetFeature\x12\x11.routeguide.Point\x1a\x13.routeguide.Feature\"\x00\x12>\n\x0cListFeatures\x12\x15.routeguide.Rectangle\x1a\x13.routeguide.Feature\"\x00\x30\x01\x12>\n\x0bRecordRoute\x12\x11.routeguide.Point\x1a\x18.routeguide.RouteSummary\"\x00(\x01\x12?\n\tRouteChat\x12\x15.routeguide.RouteNote\x1a\x15.routeguide.RouteNote\"\x00(\x01\x30\x01\x42\x36\n\x1bio.grpc.examples.routeguideB\x0fRouteGuideProtoP\x01\xa2\x02\x03RTGb\x06proto3')
)
_POINT = _descriptor.Descriptor(
name='Point',
full_name='routeguide.Point',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='latitude', full_name='routeguide.Point.latitude', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='longitude', full_name='routeguide.Point.longitude', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
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=33,
serialized_end=77,
)
_RECTANGLE = _descriptor.Descriptor(
name='Rectangle',
full_name='routeguide.Rectangle',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='lo', full_name='routeguide.Rectangle.lo', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='hi', full_name='routeguide.Rectangle.hi', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
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=79,
serialized_end=152,
)
_FEATURE = _descriptor.Descriptor(
name='Feature',
full_name='routeguide.Feature',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='routeguide.Feature.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),
_descriptor.FieldDescriptor(
name='location', full_name='routeguide.Feature.location', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
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=154,
serialized_end=214,
)
_ROUTENOTE = _descriptor.Descriptor(
name='RouteNote',
full_name='routeguide.RouteNote',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='location', full_name='routeguide.RouteNote.location', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='message', full_name='routeguide.RouteNote.message', index=1,
number=2, 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=216,
serialized_end=281,
)
_ROUTESUMMARY = _descriptor.Descriptor(
name='RouteSummary',
full_name='routeguide.RouteSummary',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='point_count', full_name='routeguide.RouteSummary.point_count', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='feature_count', full_name='routeguide.RouteSummary.feature_count', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='distance', full_name='routeguide.RouteSummary.distance', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='elapsed_time', full_name='routeguide.RouteSummary.elapsed_time', index=3,
number=4, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
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=283,
serialized_end=381,
)
_RECTANGLE.fields_by_name['lo'].message_type = _POINT
_RECTANGLE.fields_by_name['hi'].message_type = _POINT
_FEATURE.fields_by_name['location'].message_type = _POINT
_ROUTENOTE.fields_by_name['location'].message_type = _POINT
DESCRIPTOR.message_types_by_name['Point'] = _POINT
DESCRIPTOR.message_types_by_name['Rectangle'] = _RECTANGLE
DESCRIPTOR.message_types_by_name['Feature'] = _FEATURE
DESCRIPTOR.message_types_by_name['RouteNote'] = _ROUTENOTE
DESCRIPTOR.message_types_by_name['RouteSummary'] = _ROUTESUMMARY
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Point = _reflection.GeneratedProtocolMessageType('Point', (_message.Message,), dict(
DESCRIPTOR = _POINT,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.Point)
))
_sym_db.RegisterMessage(Point)
Rectangle = _reflection.GeneratedProtocolMessageType('Rectangle', (_message.Message,), dict(
DESCRIPTOR = _RECTANGLE,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.Rectangle)
))
_sym_db.RegisterMessage(Rectangle)
Feature = _reflection.GeneratedProtocolMessageType('Feature', (_message.Message,), dict(
DESCRIPTOR = _FEATURE,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.Feature)
))
_sym_db.RegisterMessage(Feature)
RouteNote = _reflection.GeneratedProtocolMessageType('RouteNote', (_message.Message,), dict(
DESCRIPTOR = _ROUTENOTE,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.RouteNote)
))
_sym_db.RegisterMessage(RouteNote)
RouteSummary = _reflection.GeneratedProtocolMessageType('RouteSummary', (_message.Message,), dict(
DESCRIPTOR = _ROUTESUMMARY,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.RouteSummary)
))
_sym_db.RegisterMessage(RouteSummary)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG'))
_ROUTEGUIDE = _descriptor.ServiceDescriptor(
name='RouteGuide',
full_name='routeguide.RouteGuide',
file=DESCRIPTOR,
index=0,
options=None,
serialized_start=384,
serialized_end=645,
methods=[
_descriptor.MethodDescriptor(
name='GetFeature',
full_name='routeguide.RouteGuide.GetFeature',
index=0,
containing_service=None,
input_type=_POINT,
output_type=_FEATURE,
options=None,
),
_descriptor.MethodDescriptor(
name='ListFeatures',
full_name='routeguide.RouteGuide.ListFeatures',
index=1,
containing_service=None,
input_type=_RECTANGLE,
output_type=_FEATURE,
options=None,
),
_descriptor.MethodDescriptor(
name='RecordRoute',
full_name='routeguide.RouteGuide.RecordRoute',
index=2,
containing_service=None,
input_type=_POINT,
output_type=_ROUTESUMMARY,
options=None,
),
_descriptor.MethodDescriptor(
name='RouteChat',
full_name='routeguide.RouteGuide.RouteChat',
index=3,
containing_service=None,
input_type=_ROUTENOTE,
output_type=_ROUTENOTE,
options=None,
),
])
_sym_db.RegisterServiceDescriptor(_ROUTEGUIDE)
DESCRIPTOR.services_by_name['RouteGuide'] = _ROUTEGUIDE
# @@protoc_insertion_point(module_scope)

@ -0,0 +1,113 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import route_guide_pb2 as route__guide__pb2
class RouteGuideStub(object):
"""Interface exported by the server.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
request_serializer=route__guide__pb2.Point.SerializeToString,
response_deserializer=route__guide__pb2.Feature.FromString,
)
self.ListFeatures = channel.unary_stream(
'/routeguide.RouteGuide/ListFeatures',
request_serializer=route__guide__pb2.Rectangle.SerializeToString,
response_deserializer=route__guide__pb2.Feature.FromString,
)
self.RecordRoute = channel.stream_unary(
'/routeguide.RouteGuide/RecordRoute',
request_serializer=route__guide__pb2.Point.SerializeToString,
response_deserializer=route__guide__pb2.RouteSummary.FromString,
)
self.RouteChat = channel.stream_stream(
'/routeguide.RouteGuide/RouteChat',
request_serializer=route__guide__pb2.RouteNote.SerializeToString,
response_deserializer=route__guide__pb2.RouteNote.FromString,
)
class RouteGuideServicer(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, context):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_RouteGuideServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetFeature': grpc.unary_unary_rpc_method_handler(
servicer.GetFeature,
request_deserializer=route__guide__pb2.Point.FromString,
response_serializer=route__guide__pb2.Feature.SerializeToString,
),
'ListFeatures': grpc.unary_stream_rpc_method_handler(
servicer.ListFeatures,
request_deserializer=route__guide__pb2.Rectangle.FromString,
response_serializer=route__guide__pb2.Feature.SerializeToString,
),
'RecordRoute': grpc.stream_unary_rpc_method_handler(
servicer.RecordRoute,
request_deserializer=route__guide__pb2.Point.FromString,
response_serializer=route__guide__pb2.RouteSummary.SerializeToString,
),
'RouteChat': grpc.stream_stream_rpc_method_handler(
servicer.RouteChat,
request_deserializer=route__guide__pb2.RouteNote.FromString,
response_serializer=route__guide__pb2.RouteNote.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'routeguide.RouteGuide', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))

@ -15,9 +15,7 @@
import json
import grpc
protos = grpc.protos("route_guide.proto")
import route_guide_pb2
def read_route_guide_database():
@ -25,14 +23,15 @@ def read_route_guide_database():
Returns:
The full contents of the route guide database as a sequence of
protos.Features.
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 = protos.Feature(
feature = route_guide_pb2.Feature(
name=item["name"],
location=protos.Point(latitude=item["location"]["latitude"],
longitude=item["location"]["longitude"]))
location=route_guide_pb2.Point(
latitude=item["location"]["latitude"],
longitude=item["location"]["longitude"]))
feature_list.append(feature)
return feature_list

@ -0,0 +1,31 @@
# Copyright 2016 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.
"""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',
))

@ -15,20 +15,35 @@
# limitations under the License.
load("@rules_proto//proto:defs.bzl", "proto_library")
load("//bazel:python_rules.bzl", "py_grpc_library", "py_proto_library")
proto_library(
name = "prime_proto",
srcs = ["prime.proto"],
)
py_proto_library(
name = "prime_proto_pb2",
deps = [":prime_proto"],
)
py_grpc_library(
name = "prime_proto_pb2_grpc",
srcs = [":prime_proto"],
deps = [":prime_proto_pb2"],
)
py_binary(
name = "client",
testonly = 1,
srcs = ["client.py"],
data = [
"prime.proto",
],
imports = ["."],
python_version = "PY3",
srcs_version = "PY3",
deps = [
":prime_proto_pb2",
":prime_proto_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)
@ -36,15 +51,13 @@ py_binary(
name = "server",
testonly = 1,
srcs = ["server.py"],
data = [
"prime.proto",
],
imports = ["."],
python_version = "PY3",
srcs_version = "PY3",
deps = [
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
":prime_proto_pb2",
":prime_proto_pb2_grpc",
] + select({
"//conditions:default": ["@futures//:futures"],
"//:python3": [],

@ -26,7 +26,8 @@ import sys
import grpc
protos, services = grpc.protos_and_services("prime.proto")
import prime_pb2
import prime_pb2_grpc
_PROCESS_COUNT = 8
_MAXIMUM_CANDIDATE = 10000
@ -51,7 +52,7 @@ def _initialize_worker(server_address):
global _worker_stub_singleton # pylint: disable=global-statement
_LOGGER.info('Initializing worker process.')
_worker_channel_singleton = grpc.insecure_channel(server_address)
_worker_stub_singleton = services.PrimeCheckerStub(
_worker_stub_singleton = prime_pb2_grpc.PrimeCheckerStub(
_worker_channel_singleton)
atexit.register(_shutdown_worker)
@ -59,7 +60,7 @@ def _initialize_worker(server_address):
def _run_worker_query(primality_candidate):
_LOGGER.info('Checking primality of %s.', primality_candidate)
return _worker_stub_singleton.check(
protos.PrimeCandidate(candidate=primality_candidate))
prime_pb2.PrimeCandidate(candidate=primality_candidate))
def _calculate_primes(server_address):

@ -29,7 +29,8 @@ import sys
import grpc
protos, services = grpc.protos_and_services("prime.proto")
import prime_pb2
import prime_pb2_grpc
_LOGGER = logging.getLogger(__name__)
@ -46,11 +47,11 @@ def is_prime(n):
return True
class PrimeChecker(services.PrimeCheckerServicer):
class PrimeChecker(prime_pb2_grpc.PrimeCheckerServicer):
def check(self, request, context):
_LOGGER.info('Determining primality of %s', request.candidate)
return protos.Primality(isPrime=is_prime(request.candidate))
return prime_pb2.Primality(isPrime=is_prime(request.candidate))
def _wait_forever(server):
@ -69,7 +70,7 @@ def _run_server(bind_address):
server = grpc.server(futures.ThreadPoolExecutor(
max_workers=_THREAD_CONCURRENCY,),
options=options)
services.add_PrimeCheckerServicer_to_server(PrimeChecker(), server)
prime_pb2_grpc.add_PrimeCheckerServicer_to_server(PrimeChecker(), server)
server.add_insecure_port(bind_address)
server.start()
_wait_forever(server)

@ -1,4 +1,4 @@
# Copyright 2015 gRPC authors.
# Copyright 2020 The gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -18,8 +18,11 @@ import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
# NOTE: The path to the .proto file must be reachable from an entry
# on sys.path. Use sys.path.insert or set the $PYTHONPATH variable to
# import from files located elsewhere on the filesystem.
protos, services = grpc.protos_and_services("helloworld.proto")
def run():
@ -27,8 +30,8 @@ def run():
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
stub = services.GreeterStub(channel)
response = stub.SayHello(protos.HelloRequest(name='you'))
print("Greeter client received: " + response.message)

@ -1,4 +1,4 @@
# Copyright 2015 gRPC authors.
# Copyright 2020 The gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -18,19 +18,18 @@ import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
protos, services = grpc.protos_and_services("helloworld.proto")
class Greeter(helloworld_pb2_grpc.GreeterServicer):
class Greeter(services.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
return protos.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)
services.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()

@ -1,4 +1,4 @@
// Copyright 2015 gRPC authors.
// Copyright 2020 The gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -1,111 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.routeguide";
option java_outer_classname = "RouteGuideProto";
option objc_class_prefix = "RTG";
package routeguide;
// Interface exported by the server.
service RouteGuide {
// A simple RPC.
//
// Obtains the feature at a given position.
//
// A feature with an empty name is returned if there's no feature at the given
// position.
rpc GetFeature(Point) returns (Feature) {}
// A server-to-client streaming RPC.
//
// Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
// huge number of features.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
// A client-to-server streaming RPC.
//
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
// A Bidirectional streaming RPC.
//
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
}
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
int32 latitude = 1;
int32 longitude = 2;
}
// A latitude-longitude rectangle, represented as two diagonally opposite
// points "lo" and "hi".
message Rectangle {
// One corner of the rectangle.
Point lo = 1;
// The other corner of the rectangle.
Point hi = 2;
}
// A feature names something at a given point.
//
// If a feature could not be named, the name is empty.
message Feature {
// The name of the feature.
string name = 1;
// The point where the feature is detected.
Point location = 2;
}
// A RouteNote is a message sent while at a given point.
message RouteNote {
// The location from which the message is sent.
Point location = 1;
// The message to be sent.
string message = 2;
}
// A RouteSummary is received in response to a RecordRoute rpc.
//
// It contains the number of individual points received, the number of
// detected features, and the total distance covered as the cumulative sum of
// the distance between each point.
message RouteSummary {
// The number of points received.
int32 point_count = 1;
// The number of known features passed while traversing the route.
int32 feature_count = 2;
// The distance covered in metres.
int32 distance = 3;
// The duration of the traversal in seconds.
int32 elapsed_time = 4;
}

@ -20,14 +20,15 @@ import logging
import grpc
protos, services = grpc.protos_and_services("route_guide.proto")
import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources
def make_route_note(message, latitude, longitude):
return protos.RouteNote(message=message,
location=protos.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):
@ -44,15 +45,14 @@ def guide_get_one_feature(stub, point):
def guide_get_feature(stub):
guide_get_one_feature(
stub, protos.Point(latitude=409146138, longitude=-746188906))
guide_get_one_feature(stub, protos.Point(latitude=0, longitude=0))
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 = protos.Rectangle(lo=protos.Point(latitude=400000000,
longitude=-750000000),
hi=protos.Point(latitude=420000000,
longitude=-730000000))
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)
@ -104,7 +104,7 @@ def run():
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
stub = services.RouteGuideStub(channel)
stub = route_guide_pb2_grpc.RouteGuideStub(channel)
print("-------------- GetFeature --------------")
guide_get_feature(stub)
print("-------------- ListFeatures --------------")

@ -0,0 +1,331 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: route_guide.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='route_guide.proto',
package='routeguide',
syntax='proto3',
serialized_pb=_b('\n\x11route_guide.proto\x12\nrouteguide\",\n\x05Point\x12\x10\n\x08latitude\x18\x01 \x01(\x05\x12\x11\n\tlongitude\x18\x02 \x01(\x05\"I\n\tRectangle\x12\x1d\n\x02lo\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x1d\n\x02hi\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"<\n\x07\x46\x65\x61ture\x12\x0c\n\x04name\x18\x01 \x01(\t\x12#\n\x08location\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"A\n\tRouteNote\x12#\n\x08location\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x0f\n\x07message\x18\x02 \x01(\t\"b\n\x0cRouteSummary\x12\x13\n\x0bpoint_count\x18\x01 \x01(\x05\x12\x15\n\rfeature_count\x18\x02 \x01(\x05\x12\x10\n\x08\x64istance\x18\x03 \x01(\x05\x12\x14\n\x0c\x65lapsed_time\x18\x04 \x01(\x05\x32\x85\x02\n\nRouteGuide\x12\x36\n\nGetFeature\x12\x11.routeguide.Point\x1a\x13.routeguide.Feature\"\x00\x12>\n\x0cListFeatures\x12\x15.routeguide.Rectangle\x1a\x13.routeguide.Feature\"\x00\x30\x01\x12>\n\x0bRecordRoute\x12\x11.routeguide.Point\x1a\x18.routeguide.RouteSummary\"\x00(\x01\x12?\n\tRouteChat\x12\x15.routeguide.RouteNote\x1a\x15.routeguide.RouteNote\"\x00(\x01\x30\x01\x42\x36\n\x1bio.grpc.examples.routeguideB\x0fRouteGuideProtoP\x01\xa2\x02\x03RTGb\x06proto3')
)
_POINT = _descriptor.Descriptor(
name='Point',
full_name='routeguide.Point',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='latitude', full_name='routeguide.Point.latitude', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='longitude', full_name='routeguide.Point.longitude', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
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=33,
serialized_end=77,
)
_RECTANGLE = _descriptor.Descriptor(
name='Rectangle',
full_name='routeguide.Rectangle',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='lo', full_name='routeguide.Rectangle.lo', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='hi', full_name='routeguide.Rectangle.hi', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
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=79,
serialized_end=152,
)
_FEATURE = _descriptor.Descriptor(
name='Feature',
full_name='routeguide.Feature',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='routeguide.Feature.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),
_descriptor.FieldDescriptor(
name='location', full_name='routeguide.Feature.location', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
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=154,
serialized_end=214,
)
_ROUTENOTE = _descriptor.Descriptor(
name='RouteNote',
full_name='routeguide.RouteNote',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='location', full_name='routeguide.RouteNote.location', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='message', full_name='routeguide.RouteNote.message', index=1,
number=2, 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=216,
serialized_end=281,
)
_ROUTESUMMARY = _descriptor.Descriptor(
name='RouteSummary',
full_name='routeguide.RouteSummary',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='point_count', full_name='routeguide.RouteSummary.point_count', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='feature_count', full_name='routeguide.RouteSummary.feature_count', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='distance', full_name='routeguide.RouteSummary.distance', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='elapsed_time', full_name='routeguide.RouteSummary.elapsed_time', index=3,
number=4, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
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=283,
serialized_end=381,
)
_RECTANGLE.fields_by_name['lo'].message_type = _POINT
_RECTANGLE.fields_by_name['hi'].message_type = _POINT
_FEATURE.fields_by_name['location'].message_type = _POINT
_ROUTENOTE.fields_by_name['location'].message_type = _POINT
DESCRIPTOR.message_types_by_name['Point'] = _POINT
DESCRIPTOR.message_types_by_name['Rectangle'] = _RECTANGLE
DESCRIPTOR.message_types_by_name['Feature'] = _FEATURE
DESCRIPTOR.message_types_by_name['RouteNote'] = _ROUTENOTE
DESCRIPTOR.message_types_by_name['RouteSummary'] = _ROUTESUMMARY
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Point = _reflection.GeneratedProtocolMessageType('Point', (_message.Message,), dict(
DESCRIPTOR = _POINT,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.Point)
))
_sym_db.RegisterMessage(Point)
Rectangle = _reflection.GeneratedProtocolMessageType('Rectangle', (_message.Message,), dict(
DESCRIPTOR = _RECTANGLE,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.Rectangle)
))
_sym_db.RegisterMessage(Rectangle)
Feature = _reflection.GeneratedProtocolMessageType('Feature', (_message.Message,), dict(
DESCRIPTOR = _FEATURE,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.Feature)
))
_sym_db.RegisterMessage(Feature)
RouteNote = _reflection.GeneratedProtocolMessageType('RouteNote', (_message.Message,), dict(
DESCRIPTOR = _ROUTENOTE,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.RouteNote)
))
_sym_db.RegisterMessage(RouteNote)
RouteSummary = _reflection.GeneratedProtocolMessageType('RouteSummary', (_message.Message,), dict(
DESCRIPTOR = _ROUTESUMMARY,
__module__ = 'route_guide_pb2'
# @@protoc_insertion_point(class_scope:routeguide.RouteSummary)
))
_sym_db.RegisterMessage(RouteSummary)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG'))
_ROUTEGUIDE = _descriptor.ServiceDescriptor(
name='RouteGuide',
full_name='routeguide.RouteGuide',
file=DESCRIPTOR,
index=0,
options=None,
serialized_start=384,
serialized_end=645,
methods=[
_descriptor.MethodDescriptor(
name='GetFeature',
full_name='routeguide.RouteGuide.GetFeature',
index=0,
containing_service=None,
input_type=_POINT,
output_type=_FEATURE,
options=None,
),
_descriptor.MethodDescriptor(
name='ListFeatures',
full_name='routeguide.RouteGuide.ListFeatures',
index=1,
containing_service=None,
input_type=_RECTANGLE,
output_type=_FEATURE,
options=None,
),
_descriptor.MethodDescriptor(
name='RecordRoute',
full_name='routeguide.RouteGuide.RecordRoute',
index=2,
containing_service=None,
input_type=_POINT,
output_type=_ROUTESUMMARY,
options=None,
),
_descriptor.MethodDescriptor(
name='RouteChat',
full_name='routeguide.RouteGuide.RouteChat',
index=3,
containing_service=None,
input_type=_ROUTENOTE,
output_type=_ROUTENOTE,
options=None,
),
])
_sym_db.RegisterServiceDescriptor(_ROUTEGUIDE)
DESCRIPTOR.services_by_name['RouteGuide'] = _ROUTEGUIDE
# @@protoc_insertion_point(module_scope)

@ -0,0 +1,113 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import route_guide_pb2 as route__guide__pb2
class RouteGuideStub(object):
"""Interface exported by the server.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
request_serializer=route__guide__pb2.Point.SerializeToString,
response_deserializer=route__guide__pb2.Feature.FromString,
)
self.ListFeatures = channel.unary_stream(
'/routeguide.RouteGuide/ListFeatures',
request_serializer=route__guide__pb2.Rectangle.SerializeToString,
response_deserializer=route__guide__pb2.Feature.FromString,
)
self.RecordRoute = channel.stream_unary(
'/routeguide.RouteGuide/RecordRoute',
request_serializer=route__guide__pb2.Point.SerializeToString,
response_deserializer=route__guide__pb2.RouteSummary.FromString,
)
self.RouteChat = channel.stream_stream(
'/routeguide.RouteGuide/RouteChat',
request_serializer=route__guide__pb2.RouteNote.SerializeToString,
response_deserializer=route__guide__pb2.RouteNote.FromString,
)
class RouteGuideServicer(object):
"""Interface exported by the server.
"""
def GetFeature(self, request, context):
"""A simple RPC.
Obtains the feature at a given position.
A feature with an empty name is returned if there's no feature at the given
position.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListFeatures(self, request, context):
"""A server-to-client streaming RPC.
Obtains the Features available within the given Rectangle. Results are
streamed rather than returned at once (e.g. in a response message with a
repeated field), as the rectangle may cover a large area and contain a
huge number of features.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RecordRoute(self, request_iterator, context):
"""A client-to-server streaming RPC.
Accepts a stream of Points on a route being traversed, returning a
RouteSummary when traversal is completed.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def RouteChat(self, request_iterator, context):
"""A Bidirectional streaming RPC.
Accepts a stream of RouteNotes sent while a route is being traversed,
while receiving other RouteNotes (e.g. from other users).
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_RouteGuideServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetFeature': grpc.unary_unary_rpc_method_handler(
servicer.GetFeature,
request_deserializer=route__guide__pb2.Point.FromString,
response_serializer=route__guide__pb2.Feature.SerializeToString,
),
'ListFeatures': grpc.unary_stream_rpc_method_handler(
servicer.ListFeatures,
request_deserializer=route__guide__pb2.Rectangle.FromString,
response_serializer=route__guide__pb2.Feature.SerializeToString,
),
'RecordRoute': grpc.stream_unary_rpc_method_handler(
servicer.RecordRoute,
request_deserializer=route__guide__pb2.Point.FromString,
response_serializer=route__guide__pb2.RouteSummary.SerializeToString,
),
'RouteChat': grpc.stream_stream_rpc_method_handler(
servicer.RouteChat,
request_deserializer=route__guide__pb2.RouteNote.FromString,
response_serializer=route__guide__pb2.RouteNote.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'routeguide.RouteGuide', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))

@ -15,8 +15,7 @@
import json
import grpc
protos = grpc.protos("route_guide.proto")
import route_guide_pb2
def read_route_guide_database():
@ -24,14 +23,15 @@ def read_route_guide_database():
Returns:
The full contents of the route guide database as a sequence of
protos.Features.
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 = protos.Feature(
feature = route_guide_pb2.Feature(
name=item["name"],
location=protos.Point(latitude=item["location"]["latitude"],
longitude=item["location"]["longitude"]))
location=route_guide_pb2.Point(
latitude=item["location"]["latitude"],
longitude=item["location"]["longitude"]))
feature_list.append(feature)
return feature_list

@ -20,8 +20,8 @@ import logging
import grpc
protos, services = grpc.protos_and_services("route_guide.proto")
import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources
@ -55,7 +55,7 @@ def get_distance(start, end):
return R * c
class RouteGuideServicer(services.RouteGuideServicer):
class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
"""Provides methods that implement functionality of route guide server."""
def __init__(self):
@ -64,7 +64,7 @@ class RouteGuideServicer(services.RouteGuideServicer):
def GetFeature(self, request, context):
feature = get_feature(self.db, request)
if feature is None:
return protos.Feature(name="", location=request)
return route_guide_pb2.Feature(name="", location=request)
else:
return feature
@ -96,10 +96,10 @@ class RouteGuideServicer(services.RouteGuideServicer):
prev_point = point
elapsed_time = time.time() - start_time
return protos.RouteSummary(point_count=point_count,
feature_count=feature_count,
distance=int(distance),
elapsed_time=int(elapsed_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 = []
@ -112,7 +112,8 @@ class RouteGuideServicer(services.RouteGuideServicer):
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
services.add_RouteGuideServicer_to_server(RouteGuideServicer(), server)
route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
RouteGuideServicer(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()

@ -0,0 +1,24 @@
# Copyright 2015 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.
"""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',
))

@ -18,13 +18,10 @@ py_library(
name = "wait_for_ready_example",
testonly = 1,
srcs = ["wait_for_ready_example.py"],
data = [
":helloworld.proto",
],
imports = ["."],
deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
],
)

@ -1,38 +0,0 @@
// Copyright 2015 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.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}

@ -22,7 +22,8 @@ import threading
import grpc
protos, services = grpc.protos_and_services("helloworld.proto")
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.INFO)
@ -40,15 +41,15 @@ def get_free_loopback_tcp_port():
tcp_socket.close()
class Greeter(services.GreeterServicer):
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, unused_context):
return protos.HelloReply(message='Hello, %s!' % request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def create_server(server_address):
server = grpc.server(futures.ThreadPoolExecutor())
services.add_GreeterServicer_to_server(Greeter(), server)
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
bound_port = server.add_insecure_port(server_address)
assert bound_port == int(server_address.split(':')[-1])
return server
@ -56,7 +57,7 @@ def create_server(server_address):
def process(stub, wait_for_ready=None):
try:
response = stub.SayHello(protos.HelloRequest(name='you'),
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'),
wait_for_ready=wait_for_ready)
message = response.message
except grpc.RpcError as rpc_error:
@ -83,7 +84,7 @@ def main():
# Create gRPC channel
channel = grpc.insecure_channel(server_address)
channel.subscribe(wait_for_transient_failure)
stub = services.GreeterStub(channel)
stub = helloworld_pb2_grpc.GreeterStub(channel)
# Fire an RPC without wait_for_ready
thread_disabled_wait_for_ready = threading.Thread(target=process,

@ -1,5 +1,4 @@
grpcio>=1.28.1
grpcio-tools
protobuf
grpcio-reflection
grpcio-health-checking

Loading…
Cancel
Save