您可以使用proto
's Message
class.
In [6]: import proto
In [7]: curr
Out[7]:
campaign {
resource_name: "customers/1234/campaigns/5678"
id: 9876
name: "testing 1, 2, 3"
advertising_channel_type: SEARCH
}
landing_page_view {
resource_name: "customers/1234/landingPageViews/1234567890"
unexpanded_final_url: "https://www.example.com/"
}
In [8]: proto.Message.to_dict(
...: curr,
...: use_integers_for_enums=False,
...: including_default_value_fields=False,
...: preserving_proto_field_name=True
...: )
Out[8]:
{'campaign': {'resource_name': 'customers/1234/campaigns/5678',
'advertising_channel_type': 'SEARCH',
'name': 'testing 1, 2, 3',
'id': '9876'},
'landing_page_view': {'resource_name': 'customers/1234/landingPageViews/1234567890',
'unexpanded_final_url': 'https://www.example.com/'}}
请注意,在to_dict
,所有 kwargs 默认为True
.
还有一个to_json
方法,如果您只想立即序列化消息而无需使用json.dumps
.
还值得注意的一个警告是proto
包的最近的内存泄漏 https://github.com/protocolbuffers/protobuf/issues/9917。该线程表示已发布修复程序,但我在较大数据集上使用它时的经验表明并非如此。仅仅因为某些东西在本地工作,并不意味着您将其部署到的容器可以处理相同的负载。