Basics tutorial
A basic tutorial introduction to gRPC in Python.
Basics tutorial
This tutorial provides a basic Python programmer’s introductionto working with gRPC.
By walking through this example you’ll learn how to:
- Define a service in a
.protofile. - Generate server and client code using the protocol buffer compiler.
- Use the Python gRPC API to write a simple client and server for your service.
It assumes that you have read theIntroduction to gRPC and are familiarwithprotocolbuffers. You canfind out more in theproto3 languageguide andPythongenerated codeguide.
Why use gRPC?
Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.
With gRPC we can define our service once in a.proto file and generate clientsand servers in any of gRPC’s supported languages, which in turn can be run inenvironments ranging from servers inside a large data center to your own tablet —all the complexity of communication between different languages and environments ishandled for you by gRPC. We also get all the advantages of working with protocolbuffers, including efficient serialization, a simple IDL, and easy interfaceupdating.
Example code and setup
The example code for this tutorial is ingrpc/grpc/examples/python/route_guide.To download the example, clone thegrpc repository by running the followingcommand:
git clone -b v1.76.0 --depth1 --shallow-submodules https://github.com/grpc/grpcThen change your current directory toexamples/python/route_guide in the repository:
cd grpc/examples/python/route_guideYou also should have the relevant tools installed to generate the server andclient interface code - if you don’t already, follow the setup instructions inQuick start.
Defining the service
Your first step (as you’ll know from theIntroduction to gRPC) is todefine the gRPCservice and the methodrequest andresponse types usingprotocolbuffers. You cansee the complete.proto file inexamples/protos/route_guide.proto.
To define a service, you specify a namedservice in your.proto file:
service RouteGuide {// (Method definitions not shown)}Then you definerpc methods inside your service definition, specifying theirrequest and response types. gRPC lets you define four kinds of service method,all of which are used in theRouteGuide service:
Asimple RPC where the client sends a request to the server using the stuband waits for a response to come back, just like a normal function call.
// Obtains the feature at a given position.rpc GetFeature(Point)returns (Feature) {}Aresponse-streaming RPC where the client sends a request to the server andgets a stream to read a sequence of messages back. The client reads from thereturned stream until there are no more messages. As you can see in theexample, you specify a response-streaming method by placing the
streamkeyword before theresponse type.// Obtains the Features available within the given Rectangle. Results are// streamed rather than returned at once (e.g. in a response message with a// repeated field), as the rectangle may cover a large area and contain a// huge number of features.rpc ListFeatures(Rectangle)returns (stream Feature) {}Arequest-streaming RPC where the client writes a sequence of messages andsends them to the server, again using a provided stream. Once the client hasfinished writing the messages, it waits for the server to read them all andreturn its response. You specify a request-streaming method by placing the
streamkeyword before therequest type.// Accepts a stream of Points on a route being traversed, returning a// RouteSummary when traversal is completed.rpc RecordRoute(stream Point)returns (RouteSummary) {}Abidirectionally-streaming RPC where both sides send a sequence of messagesusing a read-write stream. The two streams operate independently, so clientsand servers can read and write in whatever order they like: for example, theserver could wait to receive all the client messages before writing itsresponses, or it could alternately read a message then write a message, orsome other combination of reads and writes. The order of messages in eachstream is preserved. You specify this type of method by placing the
streamkeyword before both the request and the response.// Accepts a stream of RouteNotes sent while a route is being traversed,// while receiving other RouteNotes (e.g. from other users).rpc RouteChat(stream RouteNote)returns (stream RouteNote) {}
Your.proto file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthePoint message type:
// Points are represented as latitude-longitude pairs in the E7 representation// (degrees multiplied by 10**7 and rounded to the nearest integer).// Latitudes should be in the range +/- 90 degrees and longitude should be in// the range +/- 180 degrees (inclusive).messagePoint {int32 latitude=1;int32 longitude=2;}Generating client and server code
Next you need to generate the gRPC client and server interfaces from your.protoservice definition.
First, install the grpcio-tools package:
pip install grpcio-toolsUse the following command to generate the Python code:
python -m grpc_tools.protoc -I../../protos --python_out=. --pyi_out=. --grpc_python_out=. ../../protos/route_guide.protoNote that as we’ve already provided a version of the generated code in theexample directory, running this command regenerates the appropriate file ratherthan creates a new one. The generated code files are calledroute_guide_pb2.py androute_guide_pb2_grpc.py and contain:
- classes for the messages defined in
route_guide.proto - classes for the service defined in
route_guide.protoRouteGuideStub, which can be used by clients to invoke RouteGuide RPCsRouteGuideServicer, which defines the interface for implementationsof the RouteGuide service
- a function for the service defined in
route_guide.protoadd_RouteGuideServicer_to_server, which adds a RouteGuideServicer toagrpc.Server
Note
The2 in pb2 indicates that the generated code is following Protocol Buffers Python API version 2. Version 1 is obsolete. It has no relation to the Protocol Buffers Language version, which is the one indicated bysyntax = "proto3" orsyntax = "proto2" in a.proto file.Generating gRPC interfaces with custom package path
To generate gRPC client interfaces with a custom package path, you can use the-I parameter along with thegrpc_tools.protoc command. This approach allows you to specify a custom package name for the generated files.
Here’s an example command to generate the gRPC client interfaces with a custom package path:
python -m grpc_tools.protoc -Igrpc/example/custom/path=../../protos\ --python_out=. --grpc_python_out=.\ ../../protos/route_guide.protoThe generated files will be placed in the./grpc/example/custom/path/ directory:
./grpc/example/custom/path/route_guide_pb2.py./grpc/example/custom/path/route_guide_pb2_grpc.py
With this setup, the generatedroute_guide_pb2_grpc.py file will correctly import the protobuf definitions using the custom package structure, as shown below:
importgrpc.example.custom.path.route_guide_pb2asroute_guide_pb2By following this approach, you can ensure that the files will call each other correctly with respect to the specified package path. This method allows you to maintain a custom package structure for your gRPC client interfaces.
Creating the server
First let’s look at how you create aRouteGuide server. If you’re onlyinterested in creating gRPC clients, you can skip this section and go straighttoCreating the client (though you might find it interestinganyway!).
Creating and running aRouteGuide server breaks down into two work items:
- Implementing the servicer interface generated from our service definition withfunctions that perform the actual “work” of the service.
- Running a gRPC server to listen for requests from clients and transmitresponses.
You can find the exampleRouteGuide server inexamples/python/route_guide/route_guide_server.py.
Implementing RouteGuide
route_guide_server.py has aRouteGuideServicer class that subclasses thegenerated classroute_guide_pb2_grpc.RouteGuideServicer:
# RouteGuideServicer provides an implementation of the methods of the RouteGuide service.classRouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):RouteGuideServicer implements all theRouteGuide service methods.
Simple RPC
Let’s look at the simplest type first,GetFeature, which just gets aPointfrom the client and returns the corresponding feature information from itsdatabase in aFeature.
defGetFeature(self, request, context): feature= get_feature(self.db, request)if featureisNone:return route_guide_pb2.Feature(name="", location=request)else:return featureThe method is passed aroute_guide_pb2.Point request for the RPC, and agrpc.ServicerContext object that provides RPC-specific information such astimeout limits. It returns aroute_guide_pb2.Feature response.
Response-streaming RPC
Now let’s look at the next method.ListFeatures is a response-streaming RPCthat sends multipleFeatures to the client.
defListFeatures(self, request, context): left=min(request.lo.longitude, request.hi.longitude) right=max(request.lo.longitude, request.hi.longitude) top=max(request.lo.latitude, request.hi.latitude) bottom=min(request.lo.latitude, request.hi.latitude)for featurein self.db:if ( feature.location.longitude>= leftand feature.location.longitude<= rightand feature.location.latitude>= bottomand feature.location.latitude<= top ):yield featureHere the request message is aroute_guide_pb2.Rectangle within which theclient wants to findFeatures. Instead of returning a single response themethod yields zero or more responses.
Request-streaming RPC
The request-streaming methodRecordRoute uses aniterator ofrequest values and returns a single response value.
defRecordRoute(self, request_iterator, context): point_count=0 feature_count=0 distance=0.0 prev_point=None start_time= time.time()for pointin request_iterator: point_count+=1if get_feature(self.db, point): feature_count+=1if prev_point: distance+= get_distance(prev_point, point) prev_point= point elapsed_time= time.time()- start_timereturn route_guide_pb2.RouteSummary( point_count=point_count, feature_count=feature_count, distance=int(distance), elapsed_time=int(elapsed_time), )Bidirectional streaming RPC
Lastly let’s look at the bidirectionally-streaming methodRouteChat.
defRouteChat(self, request_iterator, context): prev_notes= []for new_notein request_iterator:for prev_notein prev_notes:if prev_note.location== new_note.location:yield prev_note prev_notes.append(new_note)This method’s semantics are a combination of those of the request-streamingmethod and the response-streaming method. It is passed an iterator of requestvalues and is itself an iterator of response values.
Starting the server
Once you have implemented all theRouteGuide methods, the next step is tostart up a gRPC server so that clients can actually use your service:
defserve(): server= grpc.server(futures.ThreadPoolExecutor(max_workers=10)) route_guide_pb2_grpc.add_RouteGuideServicer_to_server(RouteGuideServicer(), server) server.add_insecure_port("[::]:50051") server.start() server.wait_for_termination()The serverstart() method is non-blocking. A new thread will be instantiatedto handle requests. The thread callingserver.start() will oftennot have any other work to do in the meantime. In this case, you can callserver.wait_for_termination() to cleanly block the calling thread until theserver terminates.
Creating the client
You can see the complete example client code inexamples/python/route_guide/route_guide_client.py.
Creating a stub
To call service methods, we first need to create astub.
We instantiate theRouteGuideStub class of theroute_guide_pb2_grpcmodule, generated from our.proto.
channel= grpc.insecure_channel('localhost:50051')stub= route_guide_pb2_grpc.RouteGuideStub(channel)Calling service methods
For RPC methods that return a single response (“response-unary” methods), gRPCPython supports both synchronous (blocking) and asynchronous (non-blocking)control flow semantics. For response-streaming RPC methods, calls immediatelyreturn an iterator of response values. Calls to that iterator’snext() methodblock until the response to be yielded from the iterator becomes available.
Simple RPC
A synchronous call to the simple RPCGetFeature is nearly as straightforwardas calling a local method. The RPC call waits for the server to respond, andwill either return a response or raise an exception:
feature= stub.GetFeature(point)An asynchronous call toGetFeature is similar, but like calling a local methodasynchronously in a thread pool:
feature_future= stub.GetFeature.future(point)feature= feature_future.result()Response-streaming RPC
Calling the response-streamingListFeatures is similar to working withsequence types:
for featurein stub.ListFeatures(rectangle):Request-streaming RPC
Calling the request-streamingRecordRoute is similar to passing an iteratorto a local method. Like the simple RPC above that also returns a singleresponse, it can be called synchronously or asynchronously:
route_summary= stub.RecordRoute(point_iterator)route_summary_future= stub.RecordRoute.future(point_iterator)route_summary= route_summary_future.result()Bidirectional streaming RPC
Calling the bidirectionally-streamingRouteChat has (as is the case on theservice-side) a combination of the request-streaming and response-streamingsemantics:
for received_route_notein stub.RouteChat(sent_route_note_iterator):Try it out!
Run the server:
python route_guide_server.pyFrom a different terminal, run the client:
python route_guide_client.py