FMeinicke
FMeinicke

Reputation: 648

How to send initial metadata for a server stream in gRPC Python

I have a gRPC server that offers a server-streaming RPC. However, upon invocation of the RPC I'd like to send some metadata from the client to the server. I've found that you can use with_call with non-streaming RPCs (see the metadata example on GitHub).
This aparently doesn't work with streaming RPCs (you'd get an AttributeError: '_UnaryStreamMultiCallable' object has no attribute 'with_call').

So, my question is, how can I send metadata along with a server-streaming RPC from the client to the server? Since the server can retrieve the invocation metadata there must be a way to send it from the client, as well.

Upvotes: 1

Views: 2564

Answers (1)

FMeinicke
FMeinicke

Reputation: 648

Ok, so I found out how you can send metadata with a server-streaming RPC. The only thing you need to do is to add a tuple of tuples as parameter for the metadata keyword argument like so:

stub.MyServerStreamingRPC(
    _pb2.MyServerStreamingRequest(),
    metadata=(('metadata-identifier', 'metadata-value'),)
#                                                      ^
)

The important thing here, if you're using just one metadata pair like me, is the comma after the first inner tuple. If you forget this, the argument to the metadata parameter is not recognized as a tuple and you'll get a ValueError: too many values to unpack (expected 2).
I did forget this when I first tried to simply pass the additional metadata argument, which led me to believe that it wasn't as simple as I thought. But, as it turns out it is if you know how to use Python properly :D

Upvotes: 5

Related Questions