【问题标题】:Sending back a file stream from GRPC Python Server从 GRPC Python 服务器发回文件流
【发布时间】:2019-02-11 07:42:19
【问题描述】:

我有一个服务需要向调用客户端返回一个文件流,所以我创建了这个 proto 文件。

service Sample {
     rpc getSomething(Request) returns (stream Response){}
}

message Request {

}

message Response {
    bytes data = 1;
}

服务器收到这个后,需要读取一些source.txt文件,然后写回客户端 作为字节流。只是想问一下这是在 Python GRPC 服务器中执行此操作的正确方法吗?

fileName = "source.txt"
with open(file_name, 'r') as content_file:
    content = content_file.read()
    response.data = content.encode()
    yield response

我找不到与此相关的任何示例。

【问题讨论】:

标签: python grpc grpc-python


【解决方案1】:

这看起来基本正确,但由于您尚未与我们共享您的所有服务端代码,因此很难确定。我建议的一些调整是 (1) 首先将文件作为二进制内容读取,(2) 尽早退出 with 语句,(3) 仅在构建后才构建响应消息其data 字段的值,以及 (4) 从文件名中创建一个模块范围的模块私有常量。比如:

with open(_CONTENT_FILE_NAME, 'rb') as content_file:
    content = content_file.read()
yield my_generated_module_pb2.Response(data=content)

。你怎么看?

【讨论】:

    【解决方案2】:

    一种选择是懒惰地读取二进制文件并产生每个块。注意,这是未经测试的代码:

    def read_bytes(file_, num_bytes):
        while True:
            bin = file_.read(num_bytes)
            if len(bin) != num_bytes:
                break
            yield bin   
    
    class ResponseStreamer(Sample_pb2_grpc.SampleServicer):
        def getSomething(request, context):
            with open('test.bin', 'rb') as f:
                for rec in read_bytes(f, 4):
                    yield Sample_pb2.Response(data=rec)
    

    缺点是您将在流打开时打开文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-28
      • 2023-03-27
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2020-09-09
      相关资源
      最近更新 更多