【问题标题】:How do you create a Protobuf Struct from a Python Dict?如何从 Python 字典创建 Protobuf 结构?
【发布时间】:2019-10-11 17:04:21
【问题描述】:

我得到以下属性错误

AttributeError: 'Struct' 对象没有属性 'fields'

如果我想使用google.protobuf.internal.well_known_types.Structupdate方法

Protobuf 版本是 3.71。


MWE

from google.protobuf.internal.well_known_types import Struct

s = Struct()
s.update({"key": "value"})

这个问题的更大背景是我想在 python 中创建一个带有google.protobuf.Struct 字段的消息,用于发送以传递给生成的 RPC 客户端。

有人可以帮忙吗?

【问题讨论】:

    标签: python-3.x dictionary struct protocol-buffers


    【解决方案1】:

    好的,我在写完问题后立即发现了如何做到这一点。将答案留给可能最终遇到此问题的任何人。

    我们必须从google.protobuf.struct_pb2 导入Struct。然后update 将毫无问题地工作。

    因此,

    from google.protobuf.struct_pb2 import Struct
    
    s = Struct()
    s.update({"key": "value"})
    

    将返回一个具有表示的对象

    fields {
      key: "key"
      value {
        string_value: "value"
      }
    }
    

    【讨论】:

    • 你知道如何从结构中获取字典吗?
    • @learn2day protobuf-to-dict 包。不过,我看不出有必要这样做的充分理由。无论如何,Python 中的结构基本上表现得像字典。
    • 谢谢!它们可以,但它们不能被 json 化,这在尝试从 api 返回时是个问题。还发现{q: v for q, v in struct.items()} 作品:)
    • @learn2day 是的,字典理解适用于最上面的项目。请记住,这只是一个浅层的转换。 ;) 您必须对所有嵌套结构递归地执行此操作。
    • 我的 protobuf 对象似乎没有更新方法。我收到错误:AttributeError: update
    【解决方案2】:

    应该很简单

    from google.protobuf.struct_pb2 import Struct
    from google.protobuf import json_format
    
    s = Struct()
    s.update({"key": "value"})
    
    json_format.MessageToDict(s)
    

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 2014-03-03
      • 2019-04-23
      • 2016-05-04
      • 2014-10-02
      • 2016-11-20
      • 1970-01-01
      • 2022-11-18
      • 2021-08-26
      相关资源
      最近更新 更多