How can I use gRPC with asyncio

Viewed 11823

Where can I find examples of using gRPC with asyncio In particular, how to create a client using gRPC and asyncio

3 Answers

As of version 1.32, gRPC now supports asyncio in its Python API. If you're using an earlier version, you can still use the asyncio API via the experimental API: from grpc.experimental import aio. An asyncio hello world example has also been added to the gRPC repo. The following code is a copy of the example client:

import logging                                                                  
import asyncio                                                                  
from grpc import aio                                                            
                                                                                
import helloworld_pb2                                                           
import helloworld_pb2_grpc                                                      
                                                                                
                                                                                
async def run():                                                                
    # NOTE(gRPC Python Team): .close() is possible on a channel and should be    
    # used in circumstances in which the with statement does not fit the needs    
    # of the code.                                                              
    async with aio.insecure_channel('localhost:50051') as channel:              
        stub = helloworld_pb2_grpc.GreeterStub(channel)                         
        response = await stub.SayHello(helloworld_pb2.HelloRequest(name='you'))    
    print("Greeter client received: " + response.message)                       
                                                                                
                                                                                
if __name__ == '__main__':                                                      
    logging.basicConfig()                                                       
    asyncio.run(run())

See my other answer for how to implement the server.

Related