python - 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
列表。来自这里的任何指示都会很棒
解决方案
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);
}
推荐阅读
- xcode - 尝试查看 USDZ 文件时 Xcode 崩溃
- java - 禁用 Spring Boot Webclient 日志
- python - 如何在 PySpark 中导入 AnalysisException
- python-3.x - 如果找不到,如何返回“NA”而不是 null
- c++ - C++ 中哪个更快:mod (%) 或其他计数器?
- python - 如何舍入一组数组?我已经尝试过 numpy.round
- python-3.x - 替换文本时的 Flask-Sqlalchemy 数据突变
- java - 如何使用 GitLab CI-CD 克隆 git 存储库或如何在 AWS 服务器上部署 spring-boot 项目?
- phpmailer - 附件中的 PHPMailer 嵌入图像
- r - 网络中的颜色集群成员