如何使用grpc流

时间:2017-10-09 19:38:56

标签: python grpc

我正在尝试使用grpc hellostreamingworld.proto中的tutorial来更改helloworld示例。

我创建了multi_greeter_server.py

from concurrent import futures
import time

import grpc

import hellostreamingworld_pb2
import hellostreamingworld_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class MultiGreeter(hellostreamingworld_pb2_grpc.MultiGreeterServicer):
  def sayHello(self, request, context):
    print("Received message: {}".format(request))
    for greet in range(int(request.num_greetings)):
        yield hellostreamingworld_pb2.HelloReply(message='Hello, %s!' % request.name)


def serve():
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  hellostreamingworld_pb2_grpc.add_MultiGreeterServicer_to_server(MultiGreeter(), server)
  server.add_insecure_port('[::]:50051')
  server.start()
  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)


if __name__ == '__main__':
  serve()

我还创建了multigreeter_client.py

from __future__ import print_function

import grpc

import hellostreamingworld_pb2
import hellostreamingworld_pb2_grpc


def run():
  channel = grpc.insecure_channel('localhost:50051')
  stub = hellostreamingworld_pb2_grpc.MultiGreeterStub(channel)
  response = stub.sayHello(hellostreamingworld_pb2.HelloRequest(name='Marian', num_greetings='5'))
  print("Greeter client received: " + response.message)

不幸的是,我看不到客户端和服务器之间的通信。当我尝试运行客户端时(当服务器正在运行时)有一个Traceback:

Traceback (most recent call last):
  File "multi_greeter_client.py", line 35, in <module>
    run()
  File "multi_greeter_client.py", line 29, in run
    print("Greeter client received: " + response.message)
AttributeError: '_Rendezvous' object has no attribute 'message'

1 个答案:

答案 0 :(得分:1)

现在我明白了。响应作为迭代器返回。所以它应该作为迭代器处理。