我想知道如何使用Python gRPC发送自定义标头(或元数据)。我查看了文件,但我找不到任何东西。
答案 0 :(得分:7)
我想出了阅读代码。您可以向函数调用发送metadata
参数,其中metadata
是2元组的元组:
metadata = (('md-key', 'some value'),
('some-md-key', 'another value'))
response = stub.YourFunctionCall(request=request, metadata=metadata)
答案 1 :(得分:2)
请阅读example in github。 例如:
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'),
))
或者如果您想定义拦截器
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)
重要的是元数据的密钥不能包含大写字符(很长一段时间困扰我)。