gRPC Basics - Python

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 .proto file.
  • 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 theOverview and are familiarwithprotocolbuffers. You canfind out more in theproto3 languageguide andPythongenerated codeguide.

Why use gRPC?

This 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 you can define your service once in a .proto file and implementclients and servers in any of gRPC’s supported languages, which in turn can berun in environments ranging from servers inside Google to your own tablet -all the complexity of communication between different languages and environmentsis handled for you by gRPC. You also get all the advantages of working withprotocol buffers, including efficient serialization, a simple IDL, and easyinterface updating.

Example code and setup

The example code for this tutorial is ingrpc/grpc/examples/python/route_guide.To download the example, clone the grpc repository by running the followingcommand:

  1. $ git clone -b v1.28.1 https://github.com/grpc/grpc

Then change your current directory to examples/python/route_guide in the repository:

  1. $ cd grpc/examples/python/route_guide

You also should have the relevant tools installed to generate the server andclient interface code - if you don’t already, follow the setup instructions inthe Python quick start guide.

Defining the service

Your first step (as you’ll know from theOverview) is todefine the gRPC service and the method request and response types usingprotocolbuffers. You cansee the complete .proto file inexamples/protos/route_guide.proto.

To define a service, you specify a named service in your .proto file:

  1. service RouteGuide {
  2. // (Method definitions not shown)
  3. }

Then you define rpc 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 the RouteGuide service:

  • A simple 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.
  1. // Obtains the feature at a given position.
  2. rpc GetFeature(Point) returns (Feature) {}
  • A response-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 the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. rpc ListFeatures(Rectangle) returns (stream Feature) {}
  • A request-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 thestream keyword before the request type.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. rpc RecordRoute(stream Point) returns (RouteSummary) {}
  • A bidirectionally-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.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. 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’sthe Point message type:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

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:

  1. $ pip install grpcio-tools

Use the following command to generate the Python code:

  1. $ python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/route_guide.proto

Note 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 and route_guide_pb2_grpc.py and contain:

  • classes for the messages defined in route_guide.proto
  • classes for the service defined in route_guide.proto
    • RouteGuideStub, which can be used by clients to invoke RouteGuide RPCs
    • RouteGuideServicer, which defines the interface for implementationsof the RouteGuide service
  • a function for the service defined in route_guide.proto
    • add_RouteGuideServicer_to_server, which adds a RouteGuideServicer toa grpc.Server

Note

The 2 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 by syntax = "proto3" or syntax = "proto2" in a .proto file.

Creating the server

First let’s look at how you create a RouteGuide 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 a RouteGuide 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 example RouteGuide server inexamples/python/route_guide/route_guide_server.py.

Implementing RouteGuide

route_guide_server.py has a RouteGuideServicer class that subclasses thegenerated class route_guide_pb2_grpc.RouteGuideServicer:

  1. # RouteGuideServicer provides an implementation of the methods of the RouteGuide service.
  2. class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer):

RouteGuideServicer implements all the RouteGuide service methods.

Simple RPC

Let’s look at the simplest type first, GetFeature, which just gets a Pointfrom the client and returns the corresponding feature information from itsdatabase in a Feature.

  1. def GetFeature(self, request, context):
  2. feature = get_feature(self.db, request)
  3. if feature is None:
  4. return route_guide_pb2.Feature(name="", location=request)
  5. else:
  6. return feature

The method is passed a route_guide_pb2.Point request for the RPC, and agrpc.ServicerContext object that provides RPC-specific information such astimeout limits. It returns a route_guide_pb2.Feature response.

Response-streaming RPC

Now let’s look at the next method. ListFeatures is a response-streaming RPCthat sends multiple Features to the client.

  1. def ListFeatures(self, request, context):
  2. left = min(request.lo.longitude, request.hi.longitude)
  3. right = max(request.lo.longitude, request.hi.longitude)
  4. top = max(request.lo.latitude, request.hi.latitude)
  5. bottom = min(request.lo.latitude, request.hi.latitude)
  6. for feature in self.db:
  7. if (feature.location.longitude >= left and
  8. feature.location.longitude <= right and
  9. feature.location.latitude >= bottom and
  10. feature.location.latitude <= top):
  11. yield feature

Here the request message is a route_guide_pb2.Rectangle within which theclient wants to find Features. Instead of returning a single response themethod yields zero or more responses.

Request-streaming RPC

The request-streaming method RecordRoute uses aniterator ofrequest values and returns a single response value.

  1. def RecordRoute(self, request_iterator, context):
  2. point_count = 0
  3. feature_count = 0
  4. distance = 0.0
  5. prev_point = None
  6. start_time = time.time()
  7. for point in request_iterator:
  8. point_count += 1
  9. if get_feature(self.db, point):
  10. feature_count += 1
  11. if prev_point:
  12. distance += get_distance(prev_point, point)
  13. prev_point = point
  14. elapsed_time = time.time() - start_time
  15. return route_guide_pb2.RouteSummary(point_count=point_count,
  16. feature_count=feature_count,
  17. distance=int(distance),
  18. elapsed_time=int(elapsed_time))

Bidirectional streaming RPC

Lastly let’s look at the bidirectionally-streaming method RouteChat.

  1. def RouteChat(self, request_iterator, context):
  2. prev_notes = []
  3. for new_note in request_iterator:
  4. for prev_note in prev_notes:
  5. if prev_note.location == new_note.location:
  6. yield prev_note
  7. 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 the RouteGuide methods, the next step is tostart up a gRPC server so that clients can actually use your service:

  1. def serve():
  2. server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  3. route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
  4. RouteGuideServicer(), server)
  5. server.add_insecure_port('[::]:50051')
  6. server.start()

Because start() does not block you may need to sleep-loop if there is nothingelse for your code to do while serving.

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 a stub.

We instantiate the RouteGuideStub class of the route_guide_pb2_grpcmodule, generated from our .proto.

  1. channel = grpc.insecure_channel('localhost:50051')
  2. 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’s next() methodblock until the response to be yielded from the iterator becomes available.

Simple RPC

A synchronous call to the simple RPC GetFeature 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:

  1. feature = stub.GetFeature(point)

An asynchronous call to GetFeature is similar, but like calling a local methodasynchronously in a thread pool:

  1. feature_future = stub.GetFeature.future(point)
  2. feature = feature_future.result()

Response-streaming RPC

Calling the response-streaming ListFeatures is similar to working withsequence types:

  1. for feature in stub.ListFeatures(rectangle):

Request-streaming RPC

Calling the request-streaming RecordRoute 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:

  1. route_summary = stub.RecordRoute(point_iterator)
  1. route_summary_future = stub.RecordRoute.future(point_iterator)
  2. route_summary = route_summary_future.result()

Bidirectional streaming RPC

Calling the bidirectionally-streaming RouteChat has (as is the case on theservice-side) a combination of the request-streaming and response-streamingsemantics:

  1. for received_route_note in stub.RouteChat(sent_route_note_iterator):

Try it out!

Run the server:

  1. $ python route_guide_server.py

From a different terminal, run the client:

  1. $ python route_guide_client.py