gRPC is an RPC framework from Google that simplifies standing your application up for remote access.
In today’s article, we’ll build a remote calculator.
Prepare your system
Before we begin, you’ll need a couple of packages to assist in creating this project.
Both grpcio and grpcio-tools can be installed with the following:
Create your definition
Before we begin, we really need a clear idea on how our service will look. This involves creating a contract which will detail the data structures and service definitions that will be utilised between system actors.
To do this, we’ll use a proto file (in the protobuf format) which we’ll use to generate our contract code.
In our application we can add, subtract, multiply and divide. This is a stateful service, so we’ll be creating sessions to conduct calculations in. A create method will create a session, where as the answer method will tear our session down, emitting the result.
Running this file through grpc_tools with the following command:
We’re now left with two automatically generated files, calc_pb2_grpc.py and calc_pb2.py. These files hold the foundations of value mashalling and service definition for us.
Implementing the server
Now that we’ve generated some stubs to get our server running, we need to supply the implementation itself. A class CalculatorServicer amongst other artifacts were generated for us. We derive this class to supply our functions out.
Here’s the Create implementation. You can see that it’s just reserving a piece of the calc_db dictionary, and storing the initial value.
request is in the shape of the message that we defined for this service. In the case of Create the input message is in the type of Number. You can see that the value attribute is being accessed.
The remainder of the implementation are the arithmetic operations along with the session closure:
Finally, we need to start accepting connections.
Standing the server up
The following code sets up the calculator.
Invoking the code
Now, we’ll create a client to invoke these services.
So, we’re setting up a session with a value of 0. We then . .
Add 5
Subtract 3
Multiply by 10
Divide by 2
We should end up with 10.
Wrapping up
This is a really simple, trivial, well studied (contrived) example of how you’d use this technology. It does demonstrate the ability to offer your python code remotely.