Debian Codegraph @

examples/python/debug/asyncio_send_message.py

raw
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())