Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send custom header (metadata) with Python gRPC?

Tags:

python

grpc

I want to know how to send custom header (or metadata) using Python gRPC. I looked into documents and I couldn't find anything.

like image 385
avi Avatar asked Jul 13 '17 04:07

avi


People also ask

Does gRPC have header?

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.

What is pb2 in gRPC?

The 2 in pb2 indicates that the generated code is following Protocol Buffers Python API version 2.

Is Python gRPC multithreaded?

gRPC Python wraps gRPC core, which uses multithreading for performance, and hence doesn't support fork() .

What is trailing metadata in gRPC?

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 ).


2 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)
like image 128
avi Avatar answered Sep 19 '22 06:09

avi


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).

like image 36
flycash Avatar answered Sep 19 '22 06:09

flycash