I want to know how to send custom header (or metadata) using Python gRPC. I looked into documents and I couldn't find anything.
3 Answers
I figured out reading the code. You can send a metadata
param to the function call, where metadata
is a tuple of 2-tuples:
metadata = (('md-key', 'some value'),
('some-md-key', 'another value'))
response = stub.YourFunctionCall(request=request, metadata=metadata)
-
6More recently this needs to be a list of 2-tuples: metadata = [('k1', 'v1'), ('k2', 'v2')] Sep 28, 2017 at 21:53
-
2If you have only one header, like for example,
metadata = (('md-key', 'some value'))
this code will fail. You have to add them as array as follows:metadata = [('md-key', 'some value')]
– AviónApr 5, 2019 at 14:01 -
2It's not so much that the request fails but that Python won't interpret that as a 2-tuple. You can also use
metadata = (('md-key', 'some value'), )
– James SFeb 21, 2020 at 2:12
Pls read the example in github. For example:
response, call = stub.SayHello.with_call(
helloworld_pb2.HelloRequest(name='you'),
metadata=(
('initial-metadata-1', 'The value should be str'),
('binary-metadata-bin',
b'With -bin surffix, the value can be bytes'),
('accesstoken', 'gRPC Python is great'),
))
Or if you want to define a interceptor
metadata = []
if client_call_details.metadata is not None:
metadata = list(client_call_details.metadata)
metadata.append((
header,
value,
))
client_call_details = _ClientCallDetails(
client_call_details.method, client_call_details.timeout, metadata,
client_call_details.credentials)
Something important is that the metadata's key can not has upper case character (It has troubled me for a long time).
-
Direct link to the example: github.com/grpc/grpc/blob/master/examples/python/metadata/… Mar 12, 2020 at 14:27
-
Metadata keys must be lowercase chars. That's just horrible and frustrating.
ValueError: metadata was invalid
– Donn LeeMay 23 at 22:46
If you metadata has one key/value you can only use list(eg: [(key, value)]) ,If you metadata has Mult k/v you should use list(eg: [(key1, value1), (key2,value2)]) or tuple(eg: ((key1, value1), (key2,value2))
-
-
please consider editing your answer to include proper formatting, and to add references and/or links to supporting materials.– OussDec 29, 2021 at 10:51