yapf examples/python

pull/13728/head
ncteisen 7 years ago
parent 8cfaf4ec4f
commit 848a749f7a
  1. 11
      examples/python/helloworld/greeter_client.py
  2. 26
      examples/python/helloworld/greeter_server.py
  3. 130
      examples/python/multiplex/multiplex_client.py
  4. 181
      examples/python/multiplex/multiplex_server.py
  5. 23
      examples/python/multiplex/route_guide_resources.py
  6. 23
      examples/python/multiplex/run_codegen.py
  7. 113
      examples/python/route_guide/route_guide_client.py
  8. 23
      examples/python/route_guide/route_guide_resources.py
  9. 175
      examples/python/route_guide/route_guide_server.py
  10. 12
      examples/python/route_guide/run_codegen.py
  11. 2
      tools/distrib/yapf_code.sh

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""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
@ -23,11 +22,11 @@ import helloworld_pb2_grpc
def run(): def run():
channel = grpc.insecure_channel('localhost:50051') channel = grpc.insecure_channel('localhost:50051')
stub = helloworld_pb2_grpc.GreeterStub(channel) stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you')) response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message) print("Greeter client received: " + response.message)
if __name__ == '__main__': if __name__ == '__main__':
run() run()

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""The Python implementation of the GRPC helloworld.Greeter server.""" """The Python implementation of the GRPC helloworld.Greeter server."""
from concurrent import futures from concurrent import futures
@ -27,20 +26,21 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2_grpc.GreeterServicer): class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context): def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve(): def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051') server.add_insecure_port('[::]:50051')
server.start() server.start()
try: try:
while True: while True:
time.sleep(_ONE_DAY_IN_SECONDS) time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt: except KeyboardInterrupt:
server.stop(0) server.stop(0)
if __name__ == '__main__': if __name__ == '__main__':
serve() serve()

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""A client that makes both Greeter and RouteGuide RPCs.""" """A client that makes both Greeter and RouteGuide RPCs."""
from __future__ import print_function from __future__ import print_function
@ -29,98 +28,99 @@ import route_guide_resources
def make_route_note(message, latitude, longitude): def make_route_note(message, latitude, longitude):
return route_guide_pb2.RouteNote( return route_guide_pb2.RouteNote(
message=message, message=message,
location=route_guide_pb2.Point(latitude=latitude, longitude=longitude)) location=route_guide_pb2.Point(latitude=latitude, longitude=longitude))
def guide_get_one_feature(route_guide_stub, point): def guide_get_one_feature(route_guide_stub, point):
feature = route_guide_stub.GetFeature(point) feature = route_guide_stub.GetFeature(point)
if not feature.location: if not feature.location:
print("Server returned incomplete feature") print("Server returned incomplete feature")
return return
if feature.name: if feature.name:
print("Feature called %s at %s" % (feature.name, feature.location)) print("Feature called %s at %s" % (feature.name, feature.location))
else: else:
print("Found no feature at %s" % feature.location) print("Found no feature at %s" % feature.location)
def guide_get_feature(route_guide_stub): def guide_get_feature(route_guide_stub):
guide_get_one_feature( guide_get_one_feature(
route_guide_stub, route_guide_stub,
route_guide_pb2.Point(latitude=409146138, longitude=-746188906)) route_guide_pb2.Point(latitude=409146138, longitude=-746188906))
guide_get_one_feature( guide_get_one_feature(route_guide_stub,
route_guide_stub, route_guide_pb2.Point(latitude=0, longitude=0)) route_guide_pb2.Point(latitude=0, longitude=0))
def guide_list_features(route_guide_stub): def guide_list_features(route_guide_stub):
rectangle = route_guide_pb2.Rectangle( rectangle = route_guide_pb2.Rectangle(
lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000), lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000),
hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000)) hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000))
print("Looking for features between 40, -75 and 42, -73") print("Looking for features between 40, -75 and 42, -73")
features = route_guide_stub.ListFeatures(rectangle) features = route_guide_stub.ListFeatures(rectangle)
for feature in features: for feature in features:
print("Feature called %s at %s" % (feature.name, feature.location)) print("Feature called %s at %s" % (feature.name, feature.location))
def generate_route(feature_list): def generate_route(feature_list):
for _ in range(0, 10): for _ in range(0, 10):
random_feature = feature_list[random.randint(0, len(feature_list) - 1)] random_feature = feature_list[random.randint(0, len(feature_list) - 1)]
print("Visiting point %s" % random_feature.location) print("Visiting point %s" % random_feature.location)
yield random_feature.location yield random_feature.location
time.sleep(random.uniform(0.5, 1.5)) time.sleep(random.uniform(0.5, 1.5))
def guide_record_route(route_guide_stub): def guide_record_route(route_guide_stub):
feature_list = route_guide_resources.read_route_guide_database() feature_list = route_guide_resources.read_route_guide_database()
route_iterator = generate_route(feature_list) route_iterator = generate_route(feature_list)
route_summary = route_guide_stub.RecordRoute(route_iterator) route_summary = route_guide_stub.RecordRoute(route_iterator)
print("Finished trip with %s points " % route_summary.point_count) print("Finished trip with %s points " % route_summary.point_count)
print("Passed %s features " % route_summary.feature_count) print("Passed %s features " % route_summary.feature_count)
print("Travelled %s meters " % route_summary.distance) print("Travelled %s meters " % route_summary.distance)
print("It took %s seconds " % route_summary.elapsed_time) print("It took %s seconds " % route_summary.elapsed_time)
def generate_messages(): def generate_messages():
messages = [ messages = [
make_route_note("First message", 0, 0), make_route_note("First message", 0, 0),
make_route_note("Second message", 0, 1), make_route_note("Second message", 0, 1),
make_route_note("Third message", 1, 0), make_route_note("Third message", 1, 0),
make_route_note("Fourth message", 0, 0), make_route_note("Fourth message", 0, 0),
make_route_note("Fifth message", 1, 0), make_route_note("Fifth message", 1, 0),
] ]
for msg in messages: for msg in messages:
print("Sending %s at %s" % (msg.message, msg.location)) print("Sending %s at %s" % (msg.message, msg.location))
yield msg yield msg
time.sleep(random.uniform(0.5, 1.0)) time.sleep(random.uniform(0.5, 1.0))
def guide_route_chat(route_guide_stub): def guide_route_chat(route_guide_stub):
responses = route_guide_stub.RouteChat(generate_messages()) responses = route_guide_stub.RouteChat(generate_messages())
for response in responses: for response in responses:
print("Received message %s at %s" % (response.message, response.location)) print("Received message %s at %s" %
(response.message, response.location))
def run(): def run():
channel = grpc.insecure_channel('localhost:50051') channel = grpc.insecure_channel('localhost:50051')
greeter_stub = helloworld_pb2_grpc.GreeterStub(channel) greeter_stub = helloworld_pb2_grpc.GreeterStub(channel)
route_guide_stub = route_guide_pb2_grpc.RouteGuideStub(channel) route_guide_stub = route_guide_pb2_grpc.RouteGuideStub(channel)
greeter_response = greeter_stub.SayHello( greeter_response = greeter_stub.SayHello(
helloworld_pb2.HelloRequest(name='you')) helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + greeter_response.message) print("Greeter client received: " + greeter_response.message)
print("-------------- GetFeature --------------") print("-------------- GetFeature --------------")
guide_get_feature(route_guide_stub) guide_get_feature(route_guide_stub)
print("-------------- ListFeatures --------------") print("-------------- ListFeatures --------------")
guide_list_features(route_guide_stub) guide_list_features(route_guide_stub)
print("-------------- RecordRoute --------------") print("-------------- RecordRoute --------------")
guide_record_route(route_guide_stub) guide_record_route(route_guide_stub)
print("-------------- RouteChat --------------") print("-------------- RouteChat --------------")
guide_route_chat(route_guide_stub) guide_route_chat(route_guide_stub)
if __name__ == '__main__': if __name__ == '__main__':
run() run()

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""A gRPC server servicing both Greeter and RouteGuide RPCs.""" """A gRPC server servicing both Greeter and RouteGuide RPCs."""
from concurrent import futures from concurrent import futures
@ -30,107 +29,111 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24
def _get_feature(feature_db, point): def _get_feature(feature_db, point):
"""Returns Feature at given location or None.""" """Returns Feature at given location or None."""
for feature in feature_db: for feature in feature_db:
if feature.location == point: if feature.location == point:
return feature return feature
return None return None
def _get_distance(start, end): def _get_distance(start, end):
"""Distance between two points.""" """Distance between two points."""
coord_factor = 10000000.0 coord_factor = 10000000.0
lat_1 = start.latitude / coord_factor lat_1 = start.latitude / coord_factor
lat_2 = end.latitude / coord_factor lat_2 = end.latitude / coord_factor
lon_1 = start.longitude / coord_factor lon_1 = start.longitude / coord_factor
lon_2 = end.longitude / coord_factor lon_2 = end.longitude / coord_factor
lat_rad_1 = math.radians(lat_1) lat_rad_1 = math.radians(lat_1)
lat_rad_2 = math.radians(lat_2) lat_rad_2 = math.radians(lat_2)
delta_lat_rad = math.radians(lat_2 - lat_1) delta_lat_rad = math.radians(lat_2 - lat_1)
delta_lon_rad = math.radians(lon_2 - lon_1) delta_lon_rad = math.radians(lon_2 - lon_1)
a = (pow(math.sin(delta_lat_rad / 2), 2) + a = (pow(math.sin(delta_lat_rad / 2), 2) +
(math.cos(lat_rad_1) * math.cos(lat_rad_2) * (math.cos(lat_rad_1) * math.cos(lat_rad_2) * pow(
pow(math.sin(delta_lon_rad / 2), 2))) math.sin(delta_lon_rad / 2), 2)))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
R = 6371000; # metres R = 6371000
return R * c; # metres
return R * c
class _GreeterServicer(helloworld_pb2_grpc.GreeterServicer): class _GreeterServicer(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context): def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, {}!'.format(request.name)) return helloworld_pb2.HelloReply(
message='Hello, {}!'.format(request.name))
class _RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer): class _RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
"""Provides methods that implement functionality of route guide server.""" """Provides methods that implement functionality of route guide server."""
def __init__(self): def __init__(self):
self.db = route_guide_resources.read_route_guide_database() self.db = route_guide_resources.read_route_guide_database()
def GetFeature(self, request, context): def GetFeature(self, request, context):
feature = _get_feature(self.db, request) feature = _get_feature(self.db, request)
if feature is None: if feature is None:
return route_guide_pb2.Feature(name="", location=request) return route_guide_pb2.Feature(name="", location=request)
else: else:
return feature return feature
def ListFeatures(self, request, context): def ListFeatures(self, request, context):
left = min(request.lo.longitude, request.hi.longitude) left = min(request.lo.longitude, request.hi.longitude)
right = max(request.lo.longitude, request.hi.longitude) right = max(request.lo.longitude, request.hi.longitude)
top = max(request.lo.latitude, request.hi.latitude) top = max(request.lo.latitude, request.hi.latitude)
bottom = min(request.lo.latitude, request.hi.latitude) bottom = min(request.lo.latitude, request.hi.latitude)
for feature in self.db: for feature in self.db:
if (feature.location.longitude >= left and if (feature.location.longitude >= left and
feature.location.longitude <= right and feature.location.longitude <= right and
feature.location.latitude >= bottom and feature.location.latitude >= bottom and
feature.location.latitude <= top): feature.location.latitude <= top):
yield feature yield feature
def RecordRoute(self, request_iterator, context): def RecordRoute(self, request_iterator, context):
point_count = 0 point_count = 0
feature_count = 0 feature_count = 0
distance = 0.0 distance = 0.0
prev_point = None prev_point = None
start_time = time.time() start_time = time.time()
for point in request_iterator: for point in request_iterator:
point_count += 1 point_count += 1
if _get_feature(self.db, point): if _get_feature(self.db, point):
feature_count += 1 feature_count += 1
if prev_point: if prev_point:
distance += _get_distance(prev_point, point) distance += _get_distance(prev_point, point)
prev_point = point prev_point = point
elapsed_time = time.time() - start_time elapsed_time = time.time() - start_time
return route_guide_pb2.RouteSummary(point_count=point_count, return route_guide_pb2.RouteSummary(
feature_count=feature_count, point_count=point_count,
distance=int(distance), feature_count=feature_count,
elapsed_time=int(elapsed_time)) distance=int(distance),
elapsed_time=int(elapsed_time))
def RouteChat(self, request_iterator, context):
prev_notes = [] def RouteChat(self, request_iterator, context):
for new_note in request_iterator: prev_notes = []
for prev_note in prev_notes: for new_note in request_iterator:
if prev_note.location == new_note.location: for prev_note in prev_notes:
yield prev_note if prev_note.location == new_note.location:
prev_notes.append(new_note) yield prev_note
prev_notes.append(new_note)
def serve(): def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(_GreeterServicer(), server) helloworld_pb2_grpc.add_GreeterServicer_to_server(_GreeterServicer(),
route_guide_pb2_grpc.add_RouteGuideServicer_to_server( server)
_RouteGuideServicer(), server) route_guide_pb2_grpc.add_RouteGuideServicer_to_server(_RouteGuideServicer(),
server.add_insecure_port('[::]:50051') server)
server.start() server.add_insecure_port('[::]:50051')
try: server.start()
while True: try:
time.sleep(_ONE_DAY_IN_SECONDS) while True:
except KeyboardInterrupt: time.sleep(_ONE_DAY_IN_SECONDS)
server.stop(0) except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__': if __name__ == '__main__':
serve() serve()

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Common resources used in the gRPC route guide example.""" """Common resources used in the gRPC route guide example."""
import json import json
@ -20,19 +19,19 @@ import route_guide_pb2
def read_route_guide_database(): def read_route_guide_database():
"""Reads the route guide database. """Reads the route guide database.
Returns: Returns:
The full contents of the route guide database as a sequence of The full contents of the route guide database as a sequence of
route_guide_pb2.Features. route_guide_pb2.Features.
""" """
feature_list = [] feature_list = []
with open("route_guide_db.json") as route_guide_db_file: with open("route_guide_db.json") as route_guide_db_file:
for item in json.load(route_guide_db_file): for item in json.load(route_guide_db_file):
feature = route_guide_pb2.Feature( feature = route_guide_pb2.Feature(
name=item["name"], name=item["name"],
location=route_guide_pb2.Point( location=route_guide_pb2.Point(
latitude=item["location"]["latitude"], latitude=item["location"]["latitude"],
longitude=item["location"]["longitude"])) longitude=item["location"]["longitude"]))
feature_list.append(feature) feature_list.append(feature)
return feature_list return feature_list

@ -11,26 +11,11 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Generates protocol messages and gRPC stubs.""" """Generates protocol messages and gRPC stubs."""
from grpc_tools import protoc from grpc_tools import protoc
protoc.main( protoc.main(('', '-I../../protos', '--python_out=.', '--grpc_python_out=.',
( '../../protos/helloworld.proto',))
'', protoc.main(('', '-I../../protos', '--python_out=.', '--grpc_python_out=.',
'-I../../protos', '../../protos/route_guide.proto',))
'--python_out=.',
'--grpc_python_out=.',
'../../protos/helloworld.proto',
)
)
protoc.main(
(
'',
'-I../../protos',
'--python_out=.',
'--grpc_python_out=.',
'../../protos/route_guide.proto',
)
)

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""The Python implementation of the gRPC route guide client.""" """The Python implementation of the gRPC route guide client."""
from __future__ import print_function from __future__ import print_function
@ -26,89 +25,91 @@ import route_guide_resources
def make_route_note(message, latitude, longitude): def make_route_note(message, latitude, longitude):
return route_guide_pb2.RouteNote( return route_guide_pb2.RouteNote(
message=message, message=message,
location=route_guide_pb2.Point(latitude=latitude, longitude=longitude)) location=route_guide_pb2.Point(latitude=latitude, longitude=longitude))
def guide_get_one_feature(stub, point): def guide_get_one_feature(stub, point):
feature = stub.GetFeature(point) feature = stub.GetFeature(point)
if not feature.location: if not feature.location:
print("Server returned incomplete feature") print("Server returned incomplete feature")
return return
if feature.name: if feature.name:
print("Feature called %s at %s" % (feature.name, feature.location)) print("Feature called %s at %s" % (feature.name, feature.location))
else: else:
print("Found no feature at %s" % feature.location) print("Found no feature at %s" % feature.location)
def guide_get_feature(stub): def guide_get_feature(stub):
guide_get_one_feature(stub, route_guide_pb2.Point(latitude=409146138, longitude=-746188906)) guide_get_one_feature(
guide_get_one_feature(stub, route_guide_pb2.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): def guide_list_features(stub):
rectangle = route_guide_pb2.Rectangle( rectangle = route_guide_pb2.Rectangle(
lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000), lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000),
hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000)) hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000))
print("Looking for features between 40, -75 and 42, -73") print("Looking for features between 40, -75 and 42, -73")
features = stub.ListFeatures(rectangle) features = stub.ListFeatures(rectangle)
for feature in features: for feature in features:
print("Feature called %s at %s" % (feature.name, feature.location)) print("Feature called %s at %s" % (feature.name, feature.location))
def generate_route(feature_list): def generate_route(feature_list):
for _ in range(0, 10): for _ in range(0, 10):
random_feature = feature_list[random.randint(0, len(feature_list) - 1)] random_feature = feature_list[random.randint(0, len(feature_list) - 1)]
print("Visiting point %s" % random_feature.location) print("Visiting point %s" % random_feature.location)
yield random_feature.location yield random_feature.location
def guide_record_route(stub): def guide_record_route(stub):
feature_list = route_guide_resources.read_route_guide_database() feature_list = route_guide_resources.read_route_guide_database()
route_iterator = generate_route(feature_list) route_iterator = generate_route(feature_list)
route_summary = stub.RecordRoute(route_iterator) route_summary = stub.RecordRoute(route_iterator)
print("Finished trip with %s points " % route_summary.point_count) print("Finished trip with %s points " % route_summary.point_count)
print("Passed %s features " % route_summary.feature_count) print("Passed %s features " % route_summary.feature_count)
print("Travelled %s meters " % route_summary.distance) print("Travelled %s meters " % route_summary.distance)
print("It took %s seconds " % route_summary.elapsed_time) print("It took %s seconds " % route_summary.elapsed_time)
def generate_messages(): def generate_messages():
messages = [ messages = [
make_route_note("First message", 0, 0), make_route_note("First message", 0, 0),
make_route_note("Second message", 0, 1), make_route_note("Second message", 0, 1),
make_route_note("Third message", 1, 0), make_route_note("Third message", 1, 0),
make_route_note("Fourth message", 0, 0), make_route_note("Fourth message", 0, 0),
make_route_note("Fifth message", 1, 0), make_route_note("Fifth message", 1, 0),
] ]
for msg in messages: for msg in messages:
print("Sending %s at %s" % (msg.message, msg.location)) print("Sending %s at %s" % (msg.message, msg.location))
yield msg yield msg
def guide_route_chat(stub): def guide_route_chat(stub):
responses = stub.RouteChat(generate_messages()) responses = stub.RouteChat(generate_messages())
for response in responses: for response in responses:
print("Received message %s at %s" % (response.message, response.location)) print("Received message %s at %s" %
(response.message, response.location))
def run(): def run():
channel = grpc.insecure_channel('localhost:50051') channel = grpc.insecure_channel('localhost:50051')
stub = route_guide_pb2_grpc.RouteGuideStub(channel) stub = route_guide_pb2_grpc.RouteGuideStub(channel)
print("-------------- GetFeature --------------") print("-------------- GetFeature --------------")
guide_get_feature(stub) guide_get_feature(stub)
print("-------------- ListFeatures --------------") print("-------------- ListFeatures --------------")
guide_list_features(stub) guide_list_features(stub)
print("-------------- RecordRoute --------------") print("-------------- RecordRoute --------------")
guide_record_route(stub) guide_record_route(stub)
print("-------------- RouteChat --------------") print("-------------- RouteChat --------------")
guide_route_chat(stub) guide_route_chat(stub)
if __name__ == '__main__': if __name__ == '__main__':
run() run()

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Common resources used in the gRPC route guide example.""" """Common resources used in the gRPC route guide example."""
import json import json
@ -20,19 +19,19 @@ import route_guide_pb2
def read_route_guide_database(): def read_route_guide_database():
"""Reads the route guide database. """Reads the route guide database.
Returns: Returns:
The full contents of the route guide database as a sequence of The full contents of the route guide database as a sequence of
route_guide_pb2.Features. route_guide_pb2.Features.
""" """
feature_list = [] feature_list = []
with open("route_guide_db.json") as route_guide_db_file: with open("route_guide_db.json") as route_guide_db_file:
for item in json.load(route_guide_db_file): for item in json.load(route_guide_db_file):
feature = route_guide_pb2.Feature( feature = route_guide_pb2.Feature(
name=item["name"], name=item["name"],
location=route_guide_pb2.Point( location=route_guide_pb2.Point(
latitude=item["location"]["latitude"], latitude=item["location"]["latitude"],
longitude=item["location"]["longitude"])) longitude=item["location"]["longitude"]))
feature_list.append(feature) feature_list.append(feature)
return feature_list return feature_list

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""The Python implementation of the gRPC route guide server.""" """The Python implementation of the gRPC route guide server."""
from concurrent import futures from concurrent import futures
@ -28,98 +27,102 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24
def get_feature(feature_db, point): def get_feature(feature_db, point):
"""Returns Feature at given location or None.""" """Returns Feature at given location or None."""
for feature in feature_db: for feature in feature_db:
if feature.location == point: if feature.location == point:
return feature return feature
return None return None
def get_distance(start, end): def get_distance(start, end):
"""Distance between two points.""" """Distance between two points."""
coord_factor = 10000000.0 coord_factor = 10000000.0
lat_1 = start.latitude / coord_factor lat_1 = start.latitude / coord_factor
lat_2 = end.latitude / coord_factor lat_2 = end.latitude / coord_factor
lon_1 = start.longitude / coord_factor lon_1 = start.longitude / coord_factor
lon_2 = end.longitude / coord_factor lon_2 = end.longitude / coord_factor
lat_rad_1 = math.radians(lat_1) lat_rad_1 = math.radians(lat_1)
lat_rad_2 = math.radians(lat_2) lat_rad_2 = math.radians(lat_2)
delta_lat_rad = math.radians(lat_2 - lat_1) delta_lat_rad = math.radians(lat_2 - lat_1)
delta_lon_rad = math.radians(lon_2 - lon_1) delta_lon_rad = math.radians(lon_2 - lon_1)
a = (pow(math.sin(delta_lat_rad / 2), 2) + a = (pow(math.sin(delta_lat_rad / 2), 2) +
(math.cos(lat_rad_1) * math.cos(lat_rad_2) * (math.cos(lat_rad_1) * math.cos(lat_rad_2) * pow(
pow(math.sin(delta_lon_rad / 2), 2))) math.sin(delta_lon_rad / 2), 2)))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
R = 6371000; # metres R = 6371000
return R * c; # metres
return R * c
class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer): class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):
"""Provides methods that implement functionality of route guide server.""" """Provides methods that implement functionality of route guide server."""
def __init__(self): def __init__(self):
self.db = route_guide_resources.read_route_guide_database() self.db = route_guide_resources.read_route_guide_database()
def GetFeature(self, request, context): def GetFeature(self, request, context):
feature = get_feature(self.db, request) feature = get_feature(self.db, request)
if feature is None: if feature is None:
return route_guide_pb2.Feature(name="", location=request) return route_guide_pb2.Feature(name="", location=request)
else: else:
return feature return feature
def ListFeatures(self, request, context): def ListFeatures(self, request, context):
left = min(request.lo.longitude, request.hi.longitude) left = min(request.lo.longitude, request.hi.longitude)
right = max(request.lo.longitude, request.hi.longitude) right = max(request.lo.longitude, request.hi.longitude)
top = max(request.lo.latitude, request.hi.latitude) top = max(request.lo.latitude, request.hi.latitude)
bottom = min(request.lo.latitude, request.hi.latitude) bottom = min(request.lo.latitude, request.hi.latitude)
for feature in self.db: for feature in self.db:
if (feature.location.longitude >= left and if (feature.location.longitude >= left and
feature.location.longitude <= right and feature.location.longitude <= right and
feature.location.latitude >= bottom and feature.location.latitude >= bottom and
feature.location.latitude <= top): feature.location.latitude <= top):
yield feature yield feature
def RecordRoute(self, request_iterator, context): def RecordRoute(self, request_iterator, context):
point_count = 0 point_count = 0
feature_count = 0 feature_count = 0
distance = 0.0 distance = 0.0
prev_point = None prev_point = None
start_time = time.time() start_time = time.time()
for point in request_iterator: for point in request_iterator:
point_count += 1 point_count += 1
if get_feature(self.db, point): if get_feature(self.db, point):
feature_count += 1 feature_count += 1
if prev_point: if prev_point:
distance += get_distance(prev_point, point) distance += get_distance(prev_point, point)
prev_point = point prev_point = point
elapsed_time = time.time() - start_time elapsed_time = time.time() - start_time
return route_guide_pb2.RouteSummary(point_count=point_count, return route_guide_pb2.RouteSummary(
feature_count=feature_count, point_count=point_count,
distance=int(distance), feature_count=feature_count,
elapsed_time=int(elapsed_time)) distance=int(distance),
elapsed_time=int(elapsed_time))
def RouteChat(self, request_iterator, context):
prev_notes = [] def RouteChat(self, request_iterator, context):
for new_note in request_iterator: prev_notes = []
for prev_note in prev_notes: for new_note in request_iterator:
if prev_note.location == new_note.location: for prev_note in prev_notes:
yield prev_note if prev_note.location == new_note.location:
prev_notes.append(new_note) yield prev_note
prev_notes.append(new_note)
def serve(): def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
route_guide_pb2_grpc.add_RouteGuideServicer_to_server( route_guide_pb2_grpc.add_RouteGuideServicer_to_server(RouteGuideServicer(),
RouteGuideServicer(), server) server)
server.add_insecure_port('[::]:50051') server.add_insecure_port('[::]:50051')
server.start() server.start()
try: try:
while True: while True:
time.sleep(_ONE_DAY_IN_SECONDS) time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt: except KeyboardInterrupt:
server.stop(0) server.stop(0)
if __name__ == '__main__': if __name__ == '__main__':
serve() serve()

@ -11,17 +11,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Runs protoc with the gRPC plugin to generate messages and gRPC stubs.""" """Runs protoc with the gRPC plugin to generate messages and gRPC stubs."""
from grpc_tools import protoc from grpc_tools import protoc
protoc.main( protoc.main(('', '-I../../protos', '--python_out=.', '--grpc_python_out=.',
( '../../protos/route_guide.proto',))
'',
'-I../../protos',
'--python_out=.',
'--grpc_python_out=.',
'../../protos/route_guide.proto',
)
)

@ -19,9 +19,11 @@ set -ex
cd "$(dirname "${0}")/../.." cd "$(dirname "${0}")/../.."
DIRS=( DIRS=(
'examples/python'
'src/python' 'src/python'
) )
EXCLUSIONS=( EXCLUSIONS=(
'*_pb2*.py'
) )
VIRTUALENV=yapf_virtual_environment VIRTUALENV=yapf_virtual_environment

Loading…
Cancel
Save