Fix up examples

pull/21458/head
Richard Belleville 5 years ago
parent 999bbf1401
commit c2c5057e9d
  1. 13
      examples/python/auth/BUILD.bazel
  2. 13
      examples/python/auth/customized_auth_client.py
  3. 17
      examples/python/auth/customized_auth_server.py
  4. 35
      examples/python/cancellation/BUILD.bazel
  5. 12
      examples/python/cancellation/client.py
  6. 8
      examples/python/cancellation/search.py
  7. 9
      examples/python/cancellation/server.py
  8. 12
      examples/python/compression/BUILD.bazel
  9. 11
      examples/python/compression/client.py
  10. 13
      examples/python/compression/server.py
  11. 14
      examples/python/data_transmission/BUILD
  12. 5
      examples/python/data_transmission/alts_client.py
  13. 4
      examples/python/data_transmission/alts_server.py
  14. 18
      examples/python/debug/BUILD.bazel
  15. 13
      examples/python/debug/debug_server.py
  16. 15
      examples/python/debug/send_message.py
  17. 16
      examples/python/errors/BUILD.bazel
  18. 11
      examples/python/errors/client.py
  19. 12
      examples/python/errors/server.py
  20. 10
      examples/python/errors/test/_error_handling_example_test.py
  21. 7
      examples/python/interceptors/default_value/greeter_client.py
  22. 8
      examples/python/interceptors/headers/greeter_client.py
  23. 7
      examples/python/interceptors/headers/greeter_server.py
  24. 6
      examples/python/metadata/metadata_client.py
  25. 6
      examples/python/metadata/metadata_server.py
  26. 10
      examples/python/multiplex/multiplex_client.py
  27. 9
      examples/python/multiplex/multiplex_server.py
  28. 29
      examples/python/multiprocessing/BUILD
  29. 7
      examples/python/multiprocessing/client.py
  30. 9
      examples/python/multiprocessing/server.py
  31. 7
      examples/python/route_guide/route_guide_client.py
  32. 8
      examples/python/route_guide/route_guide_server.py
  33. 6
      examples/python/wait_for_ready/BUILD.bazel
  34. 17
      examples/python/wait_for_ready/wait_for_ready_example.py
  35. 1
      examples/python/xds/requirements.txt
  36. 2
      tools/distrib/python/grpcio_tools/BUILD.bazel

@ -34,11 +34,13 @@ py_binary(
testonly = 1, testonly = 1,
srcs = ["customized_auth_client.py"], srcs = ["customized_auth_client.py"],
python_version = "PY3", python_version = "PY3",
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
":_credentials", ":_credentials",
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
], ],
) )
@ -47,11 +49,13 @@ py_binary(
testonly = 1, testonly = 1,
srcs = ["customized_auth_server.py"], srcs = ["customized_auth_server.py"],
python_version = "PY3", python_version = "PY3",
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
":_credentials", ":_credentials",
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
], ],
) )
@ -63,7 +67,6 @@ py_test(
":_credentials", ":_credentials",
":customized_auth_client", ":customized_auth_client",
":customized_auth_server", ":customized_auth_server",
"//examples:helloworld_py_pb2",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
], ],
) )

@ -20,10 +20,15 @@ from __future__ import print_function
import argparse import argparse
import contextlib import contextlib
import logging import logging
import os
import sys
import grpc import grpc
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../.."))
protos, services = grpc.protos_and_services("examples/protos/helloworld.proto")
from examples.python.auth import _credentials from examples.python.auth import _credentials
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -72,8 +77,8 @@ def create_client_channel(addr):
def send_rpc(channel): def send_rpc(channel):
stub = helloworld_pb2_grpc.GreeterStub(channel) stub = services.GreeterStub(channel)
request = helloworld_pb2.HelloRequest(name='you') request = protos.HelloRequest(name='you')
try: try:
response = stub.SayHello(request) response = stub.SayHello(request)
except grpc.RpcError as rpc_error: except grpc.RpcError as rpc_error:

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

@ -15,36 +15,20 @@
# limitations under the License. # limitations under the License.
load("@grpc_python_dependencies//:requirements.bzl", "requirement") 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) 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( py_binary(
name = "client", name = "client",
srcs = ["client.py"], srcs = ["client.py"],
python_version = "PY3", python_version = "PY3",
srcs_version = "PY2AND3", srcs_version = "PY2AND3",
data = [
"hash_name.proto",
],
deps = [ deps = [
":hash_name_py_pb2",
":hash_name_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
"@six", "@six",
], ],
) )
@ -53,8 +37,12 @@ py_library(
name = "search", name = "search",
srcs = ["search.py"], srcs = ["search.py"],
srcs_version = "PY2AND3", srcs_version = "PY2AND3",
data = [
"hash_name.proto",
],
deps = [ deps = [
":hash_name_py_pb2", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
], ],
) )
@ -63,9 +51,12 @@ py_binary(
srcs = ["server.py"], srcs = ["server.py"],
python_version = "PY3", python_version = "PY3",
srcs_version = "PY2AND3", srcs_version = "PY2AND3",
data = [
"hash_name.proto",
],
deps = [ deps = [
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
":hash_name_py_pb2", "//tools/distrib/python/grpcio_tools:grpc_tools",
":search", ":search",
] + select({ ] + select({
"//conditions:default": ["@futures//:futures"], "//conditions:default": ["@futures//:futures"],

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

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

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

@ -17,10 +17,12 @@ py_binary(
srcs = ["server.py"], srcs = ["server.py"],
python_version = "PY3", python_version = "PY3",
srcs_version = "PY2AND3", srcs_version = "PY2AND3",
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
], ],
) )
@ -29,10 +31,12 @@ py_binary(
srcs = ["client.py"], srcs = ["client.py"],
python_version = "PY3", python_version = "PY3",
srcs_version = "PY2AND3", srcs_version = "PY2AND3",
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
], ],
) )

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

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

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

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

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

@ -18,10 +18,12 @@ py_binary(
name = "debug_server", name = "debug_server",
testonly = 1, testonly = 1,
srcs = ["debug_server.py"], srcs = ["debug_server.py"],
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
"//src/python/grpcio_channelz/grpc_channelz/v1:grpc_channelz", "//src/python/grpcio_channelz/grpc_channelz/v1:grpc_channelz",
], ],
) )
@ -31,10 +33,12 @@ py_binary(
testonly = 1, testonly = 1,
srcs = ["send_message.py"], srcs = ["send_message.py"],
python_version = "PY3", python_version = "PY3",
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
], ],
) )
@ -53,13 +57,15 @@ py_test(
name = "_debug_example_test", name = "_debug_example_test",
srcs = ["test/_debug_example_test.py"], srcs = ["test/_debug_example_test.py"],
python_version = "PY3", python_version = "PY3",
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
":debug_server", ":debug_server",
":get_stats", ":get_stats",
":send_message", ":send_message",
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
"//src/python/grpcio_channelz/grpc_channelz/v1:grpc_channelz", "//src/python/grpcio_channelz/grpc_channelz/v1:grpc_channelz",
], ],
) )

@ -20,13 +20,16 @@ from __future__ import print_function
import argparse import argparse
import logging import logging
from concurrent import futures from concurrent import futures
import os
import random import random
import sys
import grpc import grpc
from grpc_channelz.v1 import channelz from grpc_channelz.v1 import channelz
from examples import helloworld_pb2 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../.."))
from examples import helloworld_pb2_grpc
protos, services = grpc.protos_and_services("examples/protos/helloworld.proto")
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.INFO) _LOGGER.setLevel(logging.INFO)
@ -34,7 +37,7 @@ _LOGGER.setLevel(logging.INFO)
_RANDOM_FAILURE_RATE = 0.3 _RANDOM_FAILURE_RATE = 0.3
class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer): class FaultInjectGreeter(services.GreeterServicer):
def __init__(self, failure_rate): def __init__(self, failure_rate):
self._failure_rate = failure_rate self._failure_rate = failure_rate
@ -43,12 +46,12 @@ class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer):
if random.random() < self._failure_rate: if random.random() < self._failure_rate:
context.abort(grpc.StatusCode.UNAVAILABLE, context.abort(grpc.StatusCode.UNAVAILABLE,
'Randomly injected failure.') 'Randomly injected failure.')
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) return protos.HelloReply(message='Hello, %s!' % request.name)
def create_server(addr, failure_rate): def create_server(addr, failure_rate):
server = grpc.server(futures.ThreadPoolExecutor()) server = grpc.server(futures.ThreadPoolExecutor())
helloworld_pb2_grpc.add_GreeterServicer_to_server( services.add_GreeterServicer_to_server(
FaultInjectGreeter(failure_rate), server) FaultInjectGreeter(failure_rate), server)
# Add Channelz Servicer to the gRPC server # Add Channelz Servicer to the gRPC server

@ -17,11 +17,16 @@ from __future__ import absolute_import
from __future__ import division from __future__ import division
from __future__ import print_function from __future__ import print_function
import logging
import argparse import argparse
import logging
import os
import sys
import grpc import grpc
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../.."))
protos, services = grpc.protos_and_services("examples/protos/helloworld.proto")
def process(stub, request): def process(stub, request):
@ -35,8 +40,8 @@ def process(stub, request):
def run(addr, n): def run(addr, n):
with grpc.insecure_channel(addr) as channel: with grpc.insecure_channel(addr) as channel:
stub = helloworld_pb2_grpc.GreeterStub(channel) stub = services.GreeterStub(channel)
request = helloworld_pb2.HelloRequest(name='you') request = protos.HelloRequest(name='you')
for _ in range(n): for _ in range(n):
process(stub, request) process(stub, request)

@ -18,10 +18,12 @@ py_library(
name = "client", name = "client",
testonly = 1, testonly = 1,
srcs = ["client.py"], srcs = ["client.py"],
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
"//src/python/grpcio_status/grpc_status", "//src/python/grpcio_status/grpc_status",
requirement("googleapis-common-protos"), requirement("googleapis-common-protos"),
], ],
@ -31,11 +33,13 @@ py_library(
name = "server", name = "server",
testonly = 1, testonly = 1,
srcs = ["server.py"], srcs = ["server.py"],
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
"//src/python/grpcio_status/grpc_status:grpc_status", "//src/python/grpcio_status/grpc_status:grpc_status",
"//examples:helloworld_py_pb2",
"//examples:helloworld_py_pb2_grpc",
] + select({ ] + select({
"//conditions:default": [requirement("futures")], "//conditions:default": [requirement("futures")],
"//:python3": [], "//:python3": [],
@ -51,9 +55,13 @@ py_test(
"../../../src/python/grpcio_tests", "../../../src/python/grpcio_tests",
], ],
python_version = "PY3", python_version = "PY3",
data = [
"//examples:protos/helloworld.proto",
],
deps = [ deps = [
":client", ":client",
":server", ":server",
"//tools/distrib/python/grpcio_tools:grpc_tools",
"//src/python/grpcio_tests/tests:bazel_namespace_package_hack", "//src/python/grpcio_tests/tests:bazel_namespace_package_hack",
], ],
) )

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

@ -15,7 +15,9 @@
from concurrent import futures from concurrent import futures
import logging import logging
import os
import threading import threading
import sys
import grpc import grpc
from grpc_status import rpc_status from grpc_status import rpc_status
@ -23,8 +25,8 @@ from grpc_status import rpc_status
from google.protobuf import any_pb2 from google.protobuf import any_pb2
from google.rpc import code_pb2, status_pb2, error_details_pb2 from google.rpc import code_pb2, status_pb2, error_details_pb2
from examples import helloworld_pb2 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../.."))
from examples import helloworld_pb2_grpc protos, services = grpc.protos_and_services("examples/protos/helloworld.proto")
def create_greet_limit_exceed_error_status(name): def create_greet_limit_exceed_error_status(name):
@ -43,7 +45,7 @@ def create_greet_limit_exceed_error_status(name):
) )
class LimitedGreeter(helloworld_pb2_grpc.GreeterServicer): class LimitedGreeter(services.GreeterServicer):
def __init__(self): def __init__(self):
self._lock = threading.RLock() self._lock = threading.RLock()
@ -57,12 +59,12 @@ class LimitedGreeter(helloworld_pb2_grpc.GreeterServicer):
context.abort_with_status(rpc_status.to_status(rich_status)) context.abort_with_status(rpc_status.to_status(rich_status))
else: else:
self._greeted.add(request.name) self._greeted.add(request.name)
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) return protos.HelloReply(message='Hello, %s!' % request.name)
def create_server(server_address): def create_server(server_address):
server = grpc.server(futures.ThreadPoolExecutor()) server = grpc.server(futures.ThreadPoolExecutor())
helloworld_pb2_grpc.add_GreeterServicer_to_server(LimitedGreeter(), server) services.add_GreeterServicer_to_server(LimitedGreeter(), server)
port = server.add_insecure_port(server_address) port = server.add_insecure_port(server_address)
return server, port return server, port

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

@ -15,11 +15,14 @@
from __future__ import print_function from __future__ import print_function
import logging import logging
import os
import sys
import grpc import grpc
protos, services = grpc.protos_and_services("protos/helloworld.proto", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../.."))
include_paths=["../../.."]) protos, services = grpc.protos_and_services("protos/helloworld.proto")
import default_value_client_interceptor import default_value_client_interceptor

@ -14,12 +14,16 @@
"""The Python implementation of the GRPC helloworld.Greeter client.""" """The Python implementation of the GRPC helloworld.Greeter client."""
from __future__ import print_function from __future__ import print_function
import logging import logging
import os
import sys
import grpc import grpc
protos, services = grpc.protos_and_services("protos/helloworld.protos", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../.."))
include_paths=["../../.."]) protos, services = grpc.protos_and_services("protos/helloworld.protos")
import header_manipulator_client_interceptor import header_manipulator_client_interceptor

@ -15,11 +15,14 @@
from concurrent import futures from concurrent import futures
import logging import logging
import os
import sys
import grpc import grpc
protos, services = grpc.protos_and_services("protos/helloworld.protos", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../.."))
include_paths=["../../.."]) protos, services = grpc.protos_and_services("protos/helloworld.protos")
from request_header_validator_interceptor import RequestHeaderValidatorInterceptor from request_header_validator_interceptor import RequestHeaderValidatorInterceptor

@ -15,11 +15,13 @@
from __future__ import print_function from __future__ import print_function
import logging import logging
import os
import sys
import grpc import grpc
protos, services = grpc.protos_and_services("protos/helloworld.proto", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
include_paths=["../.."]) protos, services = grpc.protos_and_services("protos/helloworld.proto")
def run(): def run():

@ -16,11 +16,13 @@
from __future__ import print_function from __future__ import print_function
from concurrent import futures from concurrent import futures
import logging import logging
import os
import sys
import grpc import grpc
protos, services = grpc.protos_and_services("protos/helloworld.proto", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
include_paths=["../.."]) protos, services = grpc.protos_and_services("protos/helloworld.proto")
class Greeter(services.GreeterServicer): class Greeter(services.GreeterServicer):

@ -18,13 +18,15 @@ from __future__ import print_function
import random import random
import time import time
import logging import logging
import os
import sys
import grpc import grpc
hw_protos, hw_services = grpc.protos_and_services("protos/helloworld.proto", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
include_paths=["../.."]) hw_protos, hw_services = grpc.protos_and_services("protos/helloworld.proto")
rg_protos, rg_services = grpc.protos_and_services("protos/route_guide.proto", rg_protos, rg_services = grpc.protos_and_services("protos/route_guide.proto")
include_paths=["../.."])
import route_guide_resources import route_guide_resources

@ -17,13 +17,14 @@ from concurrent import futures
import time import time
import math import math
import logging import logging
import os
import sys
import grpc import grpc
hw_protos, hw_services = grpc.protos_and_services("protos/helloworld.proto", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
include_paths=["../.."]) hw_protos, hw_services = grpc.protos_and_services("protos/helloworld.proto")
rg_protos, rg_services = grpc.protos_and_services("protos/route_guide.proto", rg_protos, rg_services = grpc.protos_and_services("protos/route_guide.proto")
include_paths=["../.."])
import route_guide_resources import route_guide_resources

@ -15,23 +15,6 @@
# limitations under the License. # limitations under the License.
load("@rules_proto//proto:defs.bzl", "proto_library") 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( py_binary(
name = "client", name = "client",
@ -40,10 +23,12 @@ py_binary(
imports = ["."], imports = ["."],
python_version = "PY3", python_version = "PY3",
srcs_version = "PY3", srcs_version = "PY3",
data = [
"prime.proto"
],
deps = [ deps = [
":prime_proto_pb2",
":prime_proto_pb2_grpc",
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"//tools/distrib/python/grpcio_tools:grpc_tools",
], ],
) )
@ -54,10 +39,12 @@ py_binary(
imports = ["."], imports = ["."],
python_version = "PY3", python_version = "PY3",
srcs_version = "PY3", srcs_version = "PY3",
data = [
"prime.proto"
],
deps = [ deps = [
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
":prime_proto_pb2", "//tools/distrib/python/grpcio_tools:grpc_tools",
":prime_proto_pb2_grpc",
] + select({ ] + select({
"//conditions:default": ["@futures//:futures"], "//conditions:default": ["@futures//:futures"],
"//:python3": [], "//:python3": [],

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

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

@ -17,11 +17,14 @@ from __future__ import print_function
import random import random
import logging import logging
import os
import sys
import grpc import grpc
protos, services = grpc.protos_and_services("protos/route_guide.proto", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
include_paths=["../.."])
protos, services = grpc.protos_and_services("protos/route_guide.proto")
import route_guide_resources import route_guide_resources

@ -17,11 +17,15 @@ from concurrent import futures
import time import time
import math import math
import logging import logging
import os
import sys
import grpc import grpc
protos, services = grpc.protos_and_services("protos/route_guide.proto", sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../.."))
include_paths=["../.."])
protos, services = grpc.protos_and_services("protos/route_guide.proto")
import route_guide_resources import route_guide_resources

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

@ -17,13 +17,16 @@ from __future__ import print_function
import logging import logging
from concurrent import futures from concurrent import futures
from contextlib import contextmanager from contextlib import contextmanager
import os
import socket import socket
import sys
import threading import threading
import grpc import grpc
from examples import helloworld_pb2 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../.."))
from examples import helloworld_pb2_grpc
protos, services = grpc.protos_and_services("examples/protos/helloworld.proto")
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.INFO) _LOGGER.setLevel(logging.INFO)
@ -41,15 +44,15 @@ def get_free_loopback_tcp_port():
tcp_socket.close() tcp_socket.close()
class Greeter(helloworld_pb2_grpc.GreeterServicer): class Greeter(services.GreeterServicer):
def SayHello(self, request, unused_context): def SayHello(self, request, unused_context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) return protos.HelloReply(message='Hello, %s!' % request.name)
def create_server(server_address): def create_server(server_address):
server = grpc.server(futures.ThreadPoolExecutor()) server = grpc.server(futures.ThreadPoolExecutor())
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) services.add_GreeterServicer_to_server(Greeter(), server)
bound_port = server.add_insecure_port(server_address) bound_port = server.add_insecure_port(server_address)
assert bound_port == int(server_address.split(':')[-1]) assert bound_port == int(server_address.split(':')[-1])
return server return server
@ -57,7 +60,7 @@ def create_server(server_address):
def process(stub, wait_for_ready=None): def process(stub, wait_for_ready=None):
try: try:
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'), response = stub.SayHello(protos.HelloRequest(name='you'),
wait_for_ready=wait_for_ready) wait_for_ready=wait_for_ready)
message = response.message message = response.message
except grpc.RpcError as rpc_error: except grpc.RpcError as rpc_error:
@ -84,7 +87,7 @@ def main():
# Create gRPC channel # Create gRPC channel
channel = grpc.insecure_channel(server_address) channel = grpc.insecure_channel(server_address)
channel.subscribe(wait_for_transient_failure) channel.subscribe(wait_for_transient_failure)
stub = helloworld_pb2_grpc.GreeterStub(channel) stub = services.GreeterStub(channel)
# Fire an RPC without wait_for_ready # Fire an RPC without wait_for_ready
thread_disabled_wait_for_ready = threading.Thread(target=process, thread_disabled_wait_for_ready = threading.Thread(target=process,

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

@ -15,6 +15,7 @@
package(default_visibility = [ package(default_visibility = [
"//src/python:__subpackages__", "//src/python:__subpackages__",
"//tools/distrib/python/grpcio_tools:__subpackages__", "//tools/distrib/python/grpcio_tools:__subpackages__",
"//examples/python:__subpackages__",
]) ])
load("//bazel:cython_library.bzl", "pyx_library") load("//bazel:cython_library.bzl", "pyx_library")
@ -48,4 +49,5 @@ py_library(
"//src/python/grpcio/grpc:grpcio", "//src/python/grpcio/grpc:grpcio",
"@com_google_protobuf//:protobuf_python", "@com_google_protobuf//:protobuf_python",
], ],
imports=["."],
) )

Loading…
Cancel
Save