【发布时间】:2017-12-17 16:50:00
【问题描述】:
我想知道如何使用 Python gRPC 发送自定义标头(或元数据)。我查看了文档,但找不到任何东西。
【问题讨论】:
我想知道如何使用 Python gRPC 发送自定义标头(或元数据)。我查看了文档,但找不到任何东西。
【问题讨论】:
我想通了阅读代码。您可以将metadata 参数发送到函数调用,其中metadata 是2 元组的元组:
metadata = (('md-key', 'some value'),
('some-md-key', 'another value'))
response = stub.YourFunctionCall(request=request, metadata=metadata)
【讨论】:
metadata = (('md-key', 'some value')),此代码将失败。您必须将它们添加为数组,如下所示:metadata = [('md-key', 'some value')]
metadata = (('md-key', 'some value'), )
请阅读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)
重要的是元数据的键不能有大写字符(困扰我很久了)。
如果您的元数据有一个键/值,您只能使用列表(例如:[(键,值)]),如果您的元数据有 Mult k/v,您应该使用列表(例如:[(键1,值1), (key2,value2)]) 或元组(例如:((key1, value1), (key2,value2))
【讨论】: