Search code examples
python-3.xgrpcgrpc-python

Whats the golang's `stream.Send()` equivalent in python grpc clients in bidirectional stream?


Lets say below is the proto for bi-directional stream

service RouteGuide {
  // A Bidirectional streaming RPC.
  //
  // 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) {}
}

Go defines an interface to send & rec messages inside a bidirectional stream from server to client & vice-versa : go interface. But I couldn't find the same in Python, to send the response inside the stream without making an additional RouteChat call.

Also the example provided doesnt talk about sending a request back from client

How can we send the request back to server from client from python grpc clients with in the same stream?


def generate_messages():
    messages = [
        make_route_note("First message", 0, 0),
        make_route_note("Second message", 0, 1),
        make_route_note("Third message", 1, 0),
        make_route_note("Fourth message", 0, 0),
        make_route_note("Fifth message", 1, 0),
    ]
    for msg in messages:
        print("Sending %s at %s" % (msg.message, msg.location))
        yield msg


def guide_route_chat(stub):
    responses = stub.RouteChat(generate_messages())
    for response in responses:
        print("Received message %s at %s" % (response.message, response.location))
    

Solution

  • For the sync stack (i.e. not asyncio), there is no API like this. Instead, you're expected to pass in an iterator of your outgoing requests. See this previous SO answer for an example of that.

    The asyncio API however does have a write/read API that is very similar to Go's.