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

前端 未结 2 559
野性不改
野性不改 2021-01-12 23:05

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

相关标签:
2条回答
  • 2021-01-12 23:42

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

    0 讨论(0)
  • 2021-01-12 23:54

    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)
    
    0 讨论(0)
提交回复
热议问题