I want to know how to send custom header (or metadata) using Python gRPC. I looked into documents and I couldn't find anything.
Headers passed in gRPC communication are categorized into two types: call-definition headers and custom metadata. Call-definition headers are predefined headers supported by HTTP/2. Those headers should be sent before custom metadata.
The 2 in pb2 indicates that the generated code is following Protocol Buffers Python API version 2.
gRPC Python wraps gRPC core, which uses multithreading for performance, and hence doesn't support fork() .
Abstract gRPC protocol A client signals end of its message stream by means of an underlying lower level protocol. The server-to-client direction contains an optional Initial-Metadata , followed by zero or more Payload Messages terminated with a mandatory Status and optional Status-Metadata (a.k.a., Trailing-Metadata ).
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With