我正在尝试转换消息对象
message = [id: "ff90608b-bb1f-463b-ad26-e0027e67e826"
byte_content: "PK\003\004\024\000\000\000\010\000\360\206\322R\007AMb\201\...00\000\310\031\000\000\000\000"
file_type: "application/pdf"
file_name: "cumulative-essentials-visit.pdf"
]通过
from google.protobuf.json_format import MessageToDict
dict_obj = MessageToDict(message_obj)到json,但得到了一个错误
message_descriptor = message.DESCRIPTOR
AttributeError: 'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute 'DESCRIPTOR'有什么想法吗?谢谢
发布于 2021-06-27 01:11:59
下面是一个工作示例,以及重现上面的异常。
步骤1:包含以下内容的todolist.proto文件:
syntax = "proto3";
// Not necessary for Python but should still be declared to avoid name collisions
// in the Protocol Buffers namespace and non-Python languages
package protoblog;
// Style guide prefers prefixing enum values instead of surrounding
// with an enclosing message
enum TaskState {
TASK_OPEN = 0;
TASK_IN_PROGRESS = 1;
TASK_POST_PONED = 2;
TASK_CLOSED = 3;
TASK_DONE = 4;
}
message TodoList {
int32 owner_id = 1;
string owner_name = 2;
message ListItems {
TaskState state = 1;
string task = 2;
string due_date = 3;
}
repeated ListItems todos = 3;
}步骤2:通过运行以下命令,从todolist.proto文件生成特定于python的代码:
protoc -I=. --python_out=. todolist.proto这将在当前目录todolist_pb2.py中生成一个文件
步骤3:创建一个python项目,并将todolist_pb2.py复制到其中。
步骤4:创建python模块proto_test.py,内容如下:
import json
from google.protobuf.json_format import Parse
from google.protobuf.json_format import MessageToDict
from todolist_pb2 import TodoList
todolist_json_message = {
"ownerId": "1234",
"ownerName": "Tim",
"todos": [
{
"state": "TASK_DONE",
"task": "Test ProtoBuf for Python",
"dueDate": "31.10.2019"
}
]
}
todolist_proto_message = Parse(json.dumps(todolist_json_message), TodoList())
print(todolist_proto_message)
# Successfully converts the message to dictionary
todolist_proto_message_dict = MessageToDict(todolist_proto_message)
print(todolist_proto_message_dict)
# If you try to convert a field from your message rather than entire message,
# you will get object has no attribute 'DESCRIPTOR exception'
# Examples:
# Eg.1: Produces AttributeError: 'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute
# 'DESCRIPTOR.'
todos_as_dict = MessageToDict(todolist_proto_message.todos)
# Eg.2: Produces AttributeError: 'int' object has no attribute 'DESCRIPTOR'
owner_id_as_dict = MessageToDict(todolist_proto_message.owner_id)步骤5:运行proto_test.py模块,可以看到失败的行为和成功的行为。
因此,看起来您并不是在转换实际的消息,而是从消息/响应中转换list类型的字段。因此,尝试转换整个消息,然后检索您感兴趣的字段。
如果有帮助,请告诉我。
注意:您需要确保您的计算机上安装了protoc编译器,以便将.proto文件编译为步骤2中提到的特定于python的代码。安装说明可在以下位置找到:MacOS/Linux
https://stackoverflow.com/questions/68033171
复制相似问题