asyncio_route_guide_client.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # Copyright 2020 The gRPC Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """The Python AsyncIO implementation of the gRPC route guide client."""
  15. import asyncio
  16. import logging
  17. import random
  18. from typing import Iterable, List
  19. import grpc
  20. import route_guide_pb2
  21. import route_guide_pb2_grpc
  22. import route_guide_resources
  23. def make_route_note(message: str, latitude: int,
  24. longitude: int) -> route_guide_pb2.RouteNote:
  25. return route_guide_pb2.RouteNote(
  26. message=message,
  27. location=route_guide_pb2.Point(latitude=latitude, longitude=longitude))
  28. # Performs an unary call
  29. async def guide_get_one_feature(stub: route_guide_pb2_grpc.RouteGuideStub,
  30. point: route_guide_pb2.Point) -> None:
  31. feature = await stub.GetFeature(point)
  32. if not feature.location:
  33. print("Server returned incomplete feature")
  34. return
  35. if feature.name:
  36. print(f"Feature called {feature.name} at {feature.location}")
  37. else:
  38. print(f"Found no feature at {feature.location}")
  39. async def guide_get_feature(stub: route_guide_pb2_grpc.RouteGuideStub) -> None:
  40. await guide_get_one_feature(
  41. stub, route_guide_pb2.Point(latitude=409146138, longitude=-746188906))
  42. await guide_get_one_feature(stub,
  43. route_guide_pb2.Point(latitude=0, longitude=0))
  44. # Performs a server-streaming call
  45. async def guide_list_features(
  46. stub: route_guide_pb2_grpc.RouteGuideStub) -> None:
  47. rectangle = route_guide_pb2.Rectangle(
  48. lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000),
  49. hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000))
  50. print("Looking for features between 40, -75 and 42, -73")
  51. features = stub.ListFeatures(rectangle)
  52. async for feature in features:
  53. print(f"Feature called {feature.name} at {feature.location}")
  54. def generate_route(
  55. feature_list: List[route_guide_pb2.Feature]
  56. ) -> Iterable[route_guide_pb2.Point]:
  57. for _ in range(0, 10):
  58. random_feature = random.choice(feature_list)
  59. print(f"Visiting point {random_feature.location}")
  60. yield random_feature.location
  61. # Performs a client-streaming call
  62. async def guide_record_route(stub: route_guide_pb2_grpc.RouteGuideStub) -> None:
  63. feature_list = route_guide_resources.read_route_guide_database()
  64. route_iterator = generate_route(feature_list)
  65. # gRPC AsyncIO client-streaming RPC API accepts both synchronous iterables
  66. # and async iterables.
  67. route_summary = await stub.RecordRoute(route_iterator)
  68. print(f"Finished trip with {route_summary.point_count} points")
  69. print(f"Passed {route_summary.feature_count} features")
  70. print(f"Travelled {route_summary.distance} meters")
  71. print(f"It took {route_summary.elapsed_time} seconds")
  72. def generate_messages() -> Iterable[route_guide_pb2.RouteNote]:
  73. messages = [
  74. make_route_note("First message", 0, 0),
  75. make_route_note("Second message", 0, 1),
  76. make_route_note("Third message", 1, 0),
  77. make_route_note("Fourth message", 0, 0),
  78. make_route_note("Fifth message", 1, 0),
  79. ]
  80. for msg in messages:
  81. print(f"Sending {msg.message} at {msg.location}")
  82. yield msg
  83. # Performs a bidi-streaming call
  84. async def guide_route_chat(stub: route_guide_pb2_grpc.RouteGuideStub) -> None:
  85. # gRPC AsyncIO bidi-streaming RPC API accepts both synchronous iterables
  86. # and async iterables.
  87. call = stub.RouteChat(generate_messages())
  88. async for response in call:
  89. print(f"Received message {response.message} at {response.location}")
  90. async def main() -> None:
  91. async with grpc.aio.insecure_channel('localhost:50051') as channel:
  92. stub = route_guide_pb2_grpc.RouteGuideStub(channel)
  93. print("-------------- GetFeature --------------")
  94. await guide_get_feature(stub)
  95. print("-------------- ListFeatures --------------")
  96. await guide_list_features(stub)
  97. print("-------------- RecordRoute --------------")
  98. await guide_record_route(stub)
  99. print("-------------- RouteChat --------------")
  100. await guide_route_chat(stub)
  101. if __name__ == '__main__':
  102. logging.basicConfig(level=logging.INFO)
  103. asyncio.get_event_loop().run_until_complete(main())