我能够使用具有以下语法的 grpcurl 向我们启用 gRPC、启用反射的服务器之一发送请求:
grpcurl --plaintext -d '{"test_input": "Test 1 2 3", "config": { "max_results": 3 }}' localhost:6565 myorg.myproject.v1alpha6.MyService.MyStub
这不需要了解 grpcurl 的原型(prototype)。它非常完美,因为我在测试脚本中使用它,我希望它尽可能简单。
我已经能够利用它来编写一个非常简单的 python 脚本:
import json
import subprocess
input = { "test_input": "Test 1 2 3", "config": { "max_results": 3 } }
result = subprocess.check_output(['grpcurl', '--plaintext', '-d', json.dumps(input), 'localhost:6565', 'MyStub'])
dict_result = json.loads(result)
但我不太高兴不得不调用外部进程。
我在互联网上找到的所有文档都需要下载原型(prototype)及其依赖项并使用 protoc
编译它们。我可以做到,这不是问题的对象。这里的目标是使用 Python 与使用 JSON 的服务器进行交换,而无需下载 proto。就像使用 grpcurl 一样。
这可以只使用 python 来完成吗?
最佳答案
我认为不是因为(出色的)gRPCurl 似乎没有提供您希望能够从 Python 编写脚本的 API|SDK。
正如您所注意到的,这仅适用于支持反射的 gRPC 服务器(没有原型(prototype)或原型(prototype)集)。
我认为您通过 shell 控制 gRPCurl 的方法可能是最好的方法。可能值得提出一个功能请求,看看其他人是否愿意将 gRPCurl 作为测试工具来驱动;这可能很有趣。
或者,如果您不喜欢 gRPCurl,可能还有其他支持反射的工具可以由 Python 脚本化。见:
关于python - 使用 python 将纯 JSON 发送到 gRPC 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65147911/