首页 > 解决方案 > 如何在 Python 的 proto 文件中使用嵌套类型?

问题描述

我已经对 grpc-python 进行了实验,并且能够重现 HelloWorld 以及我在 Internet 上找到的一些其他示例。但是,我不清楚如何在 proto 文件中使用嵌套类型。

syntax = "proto3";

import "google/protobuf/timestamp.proto";

/*
UUID
*/
message Uuid
{
    string value = 1;
}

message StatRequest
{
    // File UUID
    Uuid uuid = 1;
}

message StatReply
{
    Data data = 1;
    message Data
    {
        google.protobuf.Timestamp create_datetime = 1;
    }
}

我已经使用 protoc 生成了文件,并且我知道如何使用简单类型。

但是,我很难发送和接收这些复杂类型。

我不知道如何引用它们。

这是服务器代码:

from concurrent import futures
import threading
import time
import grpc
import work_pb2
import work_pb2_grpc

class Listener(work_pb2_grpc.FileServicer):
    """The listener function implements the rpc call as described in the .proto file"""

    def __init__(self):
        self.counter = 0
        self.last_print_time = time.time()

    def __str__(self):
        return self.__class__.__name__

    # HERE IS ONE PROBLEM I THINK
    def stat(self, request, context):
        return work_pb2.StatReply()


def serve():
    """The main serve function of the server.
    This opens the socket, and listens for incoming grpc conformant packets"""

    server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
    work_pb2_grpc.add_FileServicer_to_server(Listener(), server)
    server.add_insecure_port("[::]:9999")
    server.start()
    try:
        while True:
            print("Server Running : threadcount %i" % (threading.active_count()))
            time.sleep(10)
    except KeyboardInterrupt:
        print("KeyboardInterrupt")
        server.stop(0)


if __name__ == "__main__":
    serve()

和客户:

import os
import time
import grpc
import work_pb2
import work_pb2_grpc

def run():
    with grpc.insecure_channel("localhost:9999") as channel:
        stub = work_pb2_grpc.FileStub(channel)
        print(stub)

        while True:
            # HOW DO I PRINT THE MESSAGES FROM THE SERVER ?
            # I am not sure how to reference the complex type defined in my proto
            # This works with non-nested types
            # response = stub.stat(work_pb2.StatReply)
            # print(response)
            return


def close(channel):
    "Close the channel"
    channel.close()


if __name__ == "__main__":
    run()

任何建议,帮助将不胜感激,谢谢。

标签: pythongrpcgrpc-python

解决方案


推荐阅读