asyncio_send_message.py
Go to the documentation of this file.
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 """Send multiple greeting messages to the backend."""
15 
16 import argparse
17 import asyncio
18 import logging
19 
20 import grpc
21 
22 helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
23  "helloworld.proto")
24 
25 
26 async def process(stub: helloworld_pb2_grpc.GreeterStub,
27  request: helloworld_pb2.HelloRequest) -> None:
28  try:
29  response = await stub.SayHello(request)
30  except grpc.aio.AioRpcError as rpc_error:
31  print(f'Received error: {rpc_error}')
32  else:
33  print(f'Received message: {response}')
34 
35 
36 async def run(addr: str, n: int) -> None:
37  async with grpc.aio.insecure_channel(addr) as channel:
38  stub = helloworld_pb2_grpc.GreeterStub(channel)
39  request = helloworld_pb2.HelloRequest(name='you')
40  for _ in range(n):
41  await process(stub, request)
42 
43 
44 async def main() -> None:
45  parser = argparse.ArgumentParser()
46  parser.add_argument('--addr',
47  nargs=1,
48  type=str,
49  default='[::]:50051',
50  help='the address to request')
51  parser.add_argument('-n',
52  nargs=1,
53  type=int,
54  default=10,
55  help='an integer for number of messages to sent')
56  args = parser.parse_args()
57  await run(addr=args.addr, n=args.n)
58 
59 
60 if __name__ == '__main__':
61  logging.basicConfig(level=logging.INFO)
62  asyncio.get_event_loop().run_until_complete(main())
helloworld_pb2_grpc.GreeterStub
Definition: helloworld/helloworld_pb2_grpc.py:7
helloworld_pb2.HelloRequest
HelloRequest
Definition: helloworld/helloworld_pb2.py:93
capstone.range
range
Definition: third_party/bloaty/third_party/capstone/bindings/python/capstone/__init__.py:6
grpc.aio._call.AioRpcError
Definition: _call.py:60
asyncio_send_message.process
None process(helloworld_pb2_grpc.GreeterStub stub, helloworld_pb2.HelloRequest request)
Definition: asyncio_send_message.py:26
asyncio_send_message.run
None run(str addr, int n)
Definition: asyncio_send_message.py:36
main
Definition: main.py:1
asyncio_send_message.main
None main()
Definition: asyncio_send_message.py:44


grpc
Author(s):
autogenerated on Thu Mar 13 2025 02:58:35