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