【问题标题】:Python write list of dicts to protobufPython将dict列表写入protobuf
【发布时间】:2021-09-21 18:34:15
【问题描述】:

我对 protobuf 和所有这一切都很陌生,但我正在尝试获取字典列表并使用 RPC/protobuf 将它们写入服务。这是原型:

syntax = "proto3";

package twittercontent.v1;

message TwitterContentRequest {
    string messageId           = 1;
    bool isPrivate             = 2;
    string handleId            = 3;
}

message TwitterContentResponse {
    string response = 1;
}

service TwitterContentService {
    rpc TwitterContent(TwitterContentRequest) returns (TwitterContentResponse) {}
}

我也有以下 dicts 列表(这里只是测试数据):

test = [
        {"messageId": "23452345324", "isPrivate": False, "handleId": "q35jmefn"},
        {"messageId": "wegwer", "isPrivate": False, "handleId": "webwerbtetny"}
       ]

我不知道从这里开始做什么,我尝试过这样的事情:

from twittercontentservice import twittercontent_pb2

def sendMsg(test):
    result = []
    for i in test:
        unit = twittercontent_pb2.TwitterContentRequest()
        unit.messageId = i['messageId']
        unit.isPrivate = i['isPrivate']
        unit.handleId = i['handleId']
        result.append(unit)
    return result

sendMsg(test)

但我认为这不起作用,当我打印函数的结果时,它只是test 列表中最后一个元素的列表。任何来自这里的指针都会很棒

【问题讨论】:

    标签: python protocol-buffers proto


    【解决方案1】:

    您的代码原样会将test 映射到twittercontent_pb2.TwitterContentRequest 列表中

    您可以使用 print(len(sendMsg(test))) 向自己证明这一点,它应该返回 2。

    但是,这就是你正在做的一切。

    您写道您想“将它们写入服务”,但您的问题包含该服务的详细信息不足以提供答案。

    如果服务是 gRPC 服务(这些服务使用 protobuf 消息),那么您将需要创建一个 gRPC 客户端并使用该客户端将您的消息提交给该服务。

    请参阅:gRPC Basic Tutorial for Python

    【讨论】:

      【解决方案2】:

      Your proto is Wrong 根据您的原型,您在消息中请求单个字典并期望多个字典。要解决它,您需要添加一个 repeated 关键字,这样您的原型就会变成这样:

      syntax = "proto3";
      
      package twittercontent.v1;
      
      message TwitterContentRequest {
          repeated TwitterContent contentRequest = 1;
      }
      
      
      message TwitterContent
      {
          string messageId           = 1;
          bool isPrivate             = 2;
          string handleId            = 3;
      }
      
      message TwitterContentResponse {
          string response = 1;
      }
      
      service TwitterContentService {
          rpc TwitterContent(TwitterContentRequest) returns (TwitterContentResponse);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-17
        • 2021-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多