python - 异步链接 grpc 调用

标签 python grpc

是否有一种直接的方法可以在 Python 中异步链接 GRPC 调用?

这感觉像是那种“应该”可行的事情,但我似乎找不到它。

以下是我认为我应该能够做的事情的粗略想法:

class MyServer(my_grpc.MyServicer):
  def __init__(self, child_stub):
    self.child_stub_ = child_stub

  def MyMethod(self, request, context):
    child_result = self.child_stub_.ChildMethod.future(my_grpc.ChildMethodParams())

    child_result.add_done_callback(something_that_completes_MyMethod)

    return presumably_something

我在这里缺少什么吗?感觉这将是一个常见的用例,但我似乎在文档中找不到与之相关的任何内容。

最佳答案

编辑:我相信您正在尝试在一元请求/响应设置中为一个请求发送两个响应,我认为这是不可能的。相反,您应该执行一元请求和流式响应,这将允许许多响应。

客户端

import grpc
import test_pb2_grpc as pb_grpc
import test_pb2 as pb2

def test():
    channel = grpc.insecure_channel('localhost:50051')
    stub = pb_grpc.TestStub(channel=channel)

    for response in stub.Produce(pb2.Empty()):
        print(response.result)

if __name__ == '__main__':
    test()

服务器

import test_pb2_grpc as pb_grpc
import test_pb2 as pb2
import time
import grpc
from concurrent import futures


class test_servcie(pb_grpc.TestServicer):
    def Produce(self, request, context):
        my_method_results = [50, 200]
        for result in my_method_results:
            yield pb2.Resp(result=result)


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    pb_grpc.add_TestServicer_to_server(test_servcie(), server)
    server.add_insecure_port('[::]:50051')
    print("service started")
    server.start()
    try:
        while True:
            time.sleep(3600)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == '__main__':
    serve()

原型(prototype)

syntax = "proto3";

package api;


service Test {
    rpc Produce (Empty) returns (stream Resp);
}

message Empty {}


message Resp{
    int32 result = 1;
}

关于python - 异步链接 grpc 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55227862/

相关文章:

grpc - 为 Hyperledger fabric V1.0 编写 gRPC 客户端

c++11 - 编译 gRPC 时出现编译错误, `‘-std=c++11’ 对 C++/ObjC++ 有效,但对 C 无效

python - Django 数据库未迁移

Python 3.x - 创建数据框并指定列名称

python - PyQt 按钮单击和释放处理程序

python - 按值的绝对值对 Python 字典进行排序

安卓:grpc 在 Nexus 5 上失败

Go gRPC status.Error() 在运行并发请求时导致无效的内存地址

python - django 模板不存在

c++ - 获取从 grpc 客户端传输的二进制数据