首页 > 解决方案 > Python将dict列表写入protobuf

问题描述

我对 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列表。来自这里的任何指示都会很棒

标签: pythonprotocol-buffersproto

解决方案


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);
}

推荐阅读