【问题标题】:Send plain JSON to a gRPC server using python使用 python 将纯 JSON 发送到 gRPC 服务器
【发布时间】:2021-03-16 18:19:14
【问题描述】:

我可以使用带有以下语法的 grpcurl 向我们启用 gRPC、启用反射的服务器之一发送请求:

grpcurl --plaintext -d '{"test_input": "Test 1 2 3", "config": { "max_results": 3 }}' localhost:6565 myorg.myproject.v1alpha6.MyService.MyStub

这不需要来自 grpcurl 的原型知识。它非常完美,因为我在一个测试脚本中使用它,我希望尽可能简单。

我已经能够利用它编写一个非常简单的 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)

但我对不得不调用外部进程不太满意。

我在互联网上找到的所有文档都需要下载 protos 及其依赖项并使用 protoc 编译它们。我可以做到这一点,这不是问题的对象。这里的目标是使用 Python 与使用 JSON 的服务器进行交换,而无需下载 proto。就像使用 grpcurl 完成的一样。

这可以仅使用 python 完成吗?

【问题讨论】:

    标签: python json protocol-buffers grpc grpcurl


    【解决方案1】:

    我认为不是因为(优秀的)gRPCurl 似乎没有提供您希望能够从 Python 编写脚本的 API|SDK。

    如您所见,这只适用于支持反射的 gRPC 服务器(没有原型或原型集)。

    我认为您通过 shell 控制 gRPCurl 的方法可能是最好的方法。可能值得提出功能请求,看看其他人是否愿意将 gRPCurl 作为测试工具;可能会很有趣。

    或者,如果您不喜欢 gRPCurl,可能还有其他支持反射的工具可以由 Python 编写。见:

    https://github.com/grpc-ecosystem/awesome-grpc#tools-test

    【讨论】:

      【解决方案2】:

      gRPC 在传输层使用 HTTP2。 就像任何其他 RPC 框架一样,它运行一个 http 服务器,可以使用基本的 http post 请求进行查询。 您基本上可以使用 requests 包触发对 gRPC 服务器的 POST 请求

      import requests, json
      
      payload = { "test_input": "Test 1 2 3", "config": { "max_results": 3 } }
      response = requests.post("http://localhost:6565", data=json.dumps(payload))
      

      【讨论】:

      • 为什么在 requests 模块支持时使用 data= 而不是 json=
      • 代码发送 json 的字符串化版本,如 json.dumps 语句所示
      • json= 也是如此。 Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:docs.python-requests.org/en/master/user/quickstart/…
      • @ShabahatM.Ayubi 我想试一试。但是 rpc 方法名称在哪里呢?在我的例子中是myorg.myproject.v1alpha6.MyService.MyStub
      猜你喜欢
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多