gRPC python

$ pip install grpcio
$ pip install grpcio-tools
$ python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. calculator.proto

$ python -m grpc_tools.protoc -I./proto/ --python_out=./proto/ --grpc_python_out=./proto/ ./proto/calculator.proto

srv/app.py

import grpc
from concurrent import futures
import time

# import the generated classes
import proto.calculator_pb2 as pb2
import proto.calculator_pb2_grpc as pb2_grpc

# import the original calculator.py
import srv.calculator as calculator

# create a class to define the server functions, derived from
# calculator_pb2_grpc.CalculatorServicer
class CalculatorServicer(pb2_grpc.CalculatorServicer):

    # calculator.square_root is exposed here
    # the request and response are of the data type
    # calculator_pb2.Number
    def SquareRoot(self, request, context):
        response = pb2.Number()
        response.value = calculator.square_root(request.value)
        return response


# create a gRPC server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

# use the generated function `add_CalculatorServicer_to_server`
# to add the defined class to the server
pb2_grpc.add_CalculatorServicer_to_server(
    CalculatorServicer(), 
    server
)

# listen on port 50051
print('Starting server. Listening on port 50051.')
server.add_insecure_port('[::]:50051')
server.start()

# since server.start() will not block,
# a sleep-loop is added to keep alive
try:
    while True:
        time.sleep(2)
except KeyboardInterrupt:
    server.stop(0)

cli/app.py

import grpc

# import the generated classes
import proto.calculator_pb2 as pb2
import proto.calculator_pb2_grpc as pb2_grpc

def calc_square_root(input=0):
    # open a gRPC channel & create a stub (client)
    channel = grpc.insecure_channel('localhost:50051')
    stub = pb2_grpc.CalculatorStub(channel)

    # create a valid request message
    number = pb2.Number(value=input)

    # make the call
    response = stub.SquareRoot(number)

    return response.value

# et voilà
val = calc_square_root(16)
print(val)

Last updated

Was this helpful?